The lastIndexOf () method of the List interface accepts a parameter that is of type Object.
However, the add () method accepts a parameter of type E (which is the general type of the list that was defined at the time the list was created) Since add () accepts only E, this prevents the developer (or user) from adding any incompatible object to the list at compile time.
Now, the Java doc says that lastIndexOf () can throw a ClassCastException if the passed object is incompatible. However, when I run the following code in Eclipse Helios, I get no 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));
In Line 1 and Line 2, I passed incompatible objects to my List, which is of type String. However, the output I get is: -
5 -1 -1
I am not getting a ClassCastException.
If the lastIndexOf () method accepted objects of type E rather than objects of type Object, this would be prevented only at compile time. Why is this not done?
The creators of Java should have thought of some problem that might arise if it accepts E (and not an object). What harm would it be?
whitehat
source share