Reputation: 263
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?
Upvotes: 0
Views: 328
Reputation: 220
if (e == null ? it.next() == null : e.equals(it.next()))
- this is a java ternary operator
it.next() == null
is a null check(returning true or false to see if this is the last element)
if that is true
return it.previousIndex();
executes
if e is not null, then
e.equals(it.next())
executes and if thats true,
return it.previousIndex();
executes
which is the index of the element your want the index of. Hope my explanation isn't confusing.
Upvotes: 0
Reputation: 10726
I think you've misunderstood what is going on with regards to the ternary operator.
This line:
if (e == null ? it.next() == null : e.equals(it.next()))
Checks to see that e is null, if it is, then it will check that the iterator's next element is null (this effectively stops the iteration operation so as to avoid a NullPointerException), otherwise: (if e is not null - i.e. it has some value in it), perform the comparison:
e.equals(it.next())
Upvotes: 0
Reputation: 178461
The loop checks if it.next() == null
only if e == null
this is done to avoid NullPointerException when evaluating e.equals(it.next())
.
if e != null
, then the regular e.equals()
method is invoked.
null
is a valid "element" that can be inserted to a LinkedList
, 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.
Upvotes: 5
Reputation: 1206
If e
is null
, the indexOf()
method will iterate until it finds another null
element in the iterable object you have passed and return its index.
Upvotes: 0