MrROY MrROY - 3 months ago 4x
Java Question

Java : Is there any way to put a String into List<Integer>?

Interview Question :


object could be any format, not only


Yes, it's possible with casting because of type erasure, but it's a Bad Idea™ and code using the list in the normal way after doing so will throw ClassCastException.

But it's possible, in that this code runs:

List<Integer> l = new ArrayList<Integer>();

That works because by casting to the raw List type rather than the parameterized List<Integer> type, we bypass the compilation check; and at runtime, the type parameter information is (mostly) gone thanks to type erasure and so the string successfully gets added to the list.

But again, any code with a List<Integer> reference to the list that's written normally (e.g., according to the List<Integer> contract) will blow up when it tries to access that entry, because the code will try to cast the String to Integer.

Looking a bit more in-depth:

List<Integer> l = new ArrayList<Integer>();
System.out.println("Added successfully");

Iterator it = l.iterator();              // Old-fashioned raw iterator works
while (it.hasNext()) {

for (Object o : l) {                     // Enhanced for with Object works

for (Integer i : l) {                    // But this throws when it reaches the
    System.out.println(i);               // String, because String cannot be cast
}                                        // to Integer