Interview Question
Software Engineer / DevelopersCountry: United States
The problem is that while defining linkedlist, we are not enforcing any type. The problem will come while retrieving the elements from the linkedlist. Since, the type of elements are different, ClassCastException will be thrown if we mistakenly do something like.
(int)ll[1].get(1). Because, get(1) stores "red" and we cannot cast it to int.
Java 1.5 gives us a means of enforcing strict types on linkedlist at compile time through generics.
LinkedList[] ll = new LinkedList[3];
ll[1] = new LinkedList();
ll[1].add(new Integer(1));
ll[1].add(1);
ll[1].add("red");
System.out.println(ll[1].get(2));
This code works perfectly fine ... If we do not write the 2nd line ....then Null pointer exception will come. The bound should be between 0 to 2. And autoboxing is also a problem as explained above .....
generic are the new feature that has been added to the JDK 1.5
LinkedList <Object> ll = new LinkedList<Object>();//not an array to use [ ] and not mandatory to specify the size
li.add(1);//no indication of the indices for a Linked list
li.add("red");
li.add("Blue");
li.add(1.2);
- the indexes need to be from 0 to 2, regardless of Java flavor.
- Anonymous August 15, 2012- prior to 1.5, Java did not have autoboxing, so you'd need to change ll[1].add(1); to ll[1].add(new Integer(1)); This is because LinkedList can only accommodate objects, and a primitive is not an object, so you need to use a wrapper type. Starting with Java 1.5, the conversion is made automatically.
- Java 1.5 and later may warn about using LinkedList without a generic type parameter (e.g. LinkedList<Object>)