in OCP page 168, there is the following question
The explanation on page 555 of the book says that:
LinkedList implements both List and Queue. The List interface has a method to
remove by index. Since this method exists, Java does not autobox to call the other method.
Queue has only the remove by object method, so Java does autobox there. Since the number
1 is not in the list, Java does not remove anything for the Queue
I did not understand the part :
Queue has only the remove by object method
I searched the API of Queue in the following link:
and I only found this remove method:
What does OCP mean when saying that Queue has only the remove by object method?
Retrieves and removes the head of this queue. This method differs from poll only in that it throws an exception if this queue is empty.
boolean remove(Object o)
This is the remove by Object the book is speaking of.
This was careless naming IMO. The Java Collections should never have sanctioned a (List).remove(int) to remove at a specific slot within the List.
It should have been named "removeAt(int)" or similar.
This probably happened because Java Collections far predated any consideration of Auto Boxing/Unboxing (Java 5 I believe), so it never occurred to anyone that an "intention" conflict might happen.
How do we recognize that it uses E remove(int index) method from List interface instead of boolean remove(Object o) ???
In the code q.remove(1), "1" is an integer literal. That means its type is int. Since int is a Java primitive and not an Object, the JVM will use E remove(int index).
This is a case of method overloading, that is, the methods have the same name but not the same arguments. Which method is called is determined by the type and number of arguments.