A safer way to return a generic indicator object indicating failure I'm writing a singly-linked list that implements the List interface. I decided going in that I'd try to implement every method as an exercise; even the optional ones.

I started writing the ListIterator, and found the need to return the node previous to a given node for operations like add. Unfortunately, I didn't anticipate this scenario prior to writing the rest of the list, and have no way of indicating failure (failure being that the given node doesn't exist in the list), since null is a valid return if the root node is supplied. I decided to allow the caller to pass in an indicator node that would be returned if the node wasn't found. I wasn't sure the best way to handle this thought, since Node is generic.

I ended up making the indicator of type Node&lt;Object&gt;, and casting it prior to returning. I know this is dangerous though, so I made it very clear in the documentation that the method isn't safe (plus, of course, it's private).

I'd like to know if there's a less hack-ish way of dealing with this scenario though.

I didn't think including the full implementation was necessary. The names should be obvious enough (I hope). 

/**
 * Dangerous.
 * Returns the node that comes before the given node, or badNode if the
 *  node doesn't exist in the list.
 * The return must be checked against badNode prior to use!
 *  
 * @param node The node to find the predecessor of 
 * @param badNode The indicator that will be returned if node isn't in the list
 * @return The predecessor of node, or badNode if node doesn't exist.
 */
@SuppressWarnings("unchecked")
private Node&lt;E&gt; getNodeBefore(Node&lt;E&gt; node, Node&lt;Object&gt; badNode) {
    Node&lt;E&gt; curNode = getRootNode();
    Node&lt;E&gt; prevNode = null;

    while (curNode != null) {
        if (curNode == node) {
            return prevNode;
        }

    prevNode = curNode;
    curNode = curNode.getNextNode();
    }

    return (Node&lt;E&gt;)badNode;
}
A fairly clean way is to use Optionals, like these or those. So you would make getNodeBefore return an Optional&lt;Node&lt;E&gt;&gt;. 

The badNode idea is, hm, exotic to me.