This is a sample implementation of indexOf() in LinkedList on Oracle’s website. I’m a little confused on how the if loop works here:
public int indexOf(E e) {
for (ListIterator<E> it = listIterator(); it.hasNext(); )
if (e == null ? it.next() == null : e.equals(it.next()))
return it.previousIndex();
// Element not found
return -1;
}
So the ListIterator object is created at the head of the list. for loop goes on until the iterator reaches the list’s end, and the if loop checks if the target object is found. The part I did not understand though, is that why does the if loop check it.next() == null when e == null? Could someone help walk me through how it’s done when input e is null?
The loop checks if
it.next() == nullonly ife == nullthis is done to avoid NullPointerException when evaluatinge.equals(it.next()).if
e != null, then the regulare.equals()method is invoked.nullis a valid “element” that can be inserted to aLinkedList, so this must be taken into consideration.The position of the last element is not inserted. Note that unlike the text book data structure where the last element in a Linked List is
null, in here – when you get to the last element –it.hasNext()will be evaluated to false, without letting you see this “junk” element.