The lastIndexOf() method of List interface accepts a parameter which is of type Object.
However, the add() method accepts a parameter of type E (which is the generic-type of the List which is defined at the time of creating a List) Since add() accepts only E, this prevents the developer (or user) to add any incompatible object to the list at compile-time itself.
Now, Java doc says that lastIndexOf() can throw ClassCastException if the object passed is incompatible. However, when I run the following code in Eclipse Helios I don't get any Exception :-
package scjp.collection.list;
import java.util.ArrayList;
import java.util.List;
public class LastIndexOf {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("some");
list.add("thing");
list.add("at");
list.add("last");
list.add("and");
list.add("at");
list.add("again");
System.out.println(list.lastIndexOf("at"));
System.out.println(list.lastIndexOf(10)); // # 1
System.out.println(list.lastIndexOf(new LastIndexOf())); // # 2
}
}
At Line 1 and Line 2, I have passed incompatible objects to my List which is of type String. However, the output that I get is :-
5
-1
-1
I get no ClassCastException.
Had the lastIndexOf() method been accepting objects of type E rather than objects of type Object, this would have been prevented at compile-time only. Why is this not done??
Java creators must have thought some problem that could occur if it accept E (and not Object). What harm would it be??