indexOf
returns the index of the first occurence which is the same (according to the equals method) in the List. That's why you see both 1 printed.
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
And you can see the implementation (for ArrayList
, but that's the same idea for a LinkedList
except that you iterate other the nodes):
229 public int indexOf(Object o) {
230 if (o == null) {
231 for (int i = 0; i < size; i++)
232 if (elementData[i]==null)
233 return i;
234 } else {
235 for (int i = 0; i < size; i++)
236 if (o.equals(elementData[i]))
237 return i;
238 }
239 return -1;
240 }
If you want to print the index associated, you can use a counter that you increment at each iteration.
int index = 0;
for (Person display : deletePeople) {
if(display.equals(checkPerson)){
System.out.println((display.getFirstName() + " " + display.getLastName() + " " + index));
}
index++;
}
It would also be possible with a standard for loop.
for(int i = 0; i < deletePeople.size(); i++){
Person display = deletePeople.get(i);
if(display.equals(checkPerson)){
System.out.println((display.getFirstName() + " " + display.getLastName() + " " + i));
}
}
However be careful with the latter implementation because if the underlying representation of the list is a LinkedList
the complexity of the above loop would be O(n^2)
instead of O(n)
.