I have read the thread Difference in LinkedList, queue vs list, but still don't understand the following code behavior:
List<Integer> l = new LinkedList<>();
l.add(10);
l.add(12);
l.remove(1); // removes index 1
System.out.println(l); // outputs [10]
Queue<Integer> q2 = new LinkedList<>();
q2.add(10);
q2.add(12);
q2.remove(1); // tries to remove object 1
System.out.println(q2); // outputs [10, 12]
I know, why the outputs differ:
- in case of
l
the callremove(1)
removes the element with the index1
- in case of
q
the callremove(1)
tries to remove an object1
, but there are only Integers10
and12
.
If I take a closer look to the interfaces:
- Queue does not have a
remove(int)
method, but inherits aremove(Object)
method from Collection. - List has a
remove(int index)
andremove(Object o)
method.
So far, so good.
But: I do not understand, how Java is able to invoke two different methods while using the same syntax (remove(1)
)?