Search⌘ K
AI Features

Erasure

Explore Java generics erasure to understand why List<Integer> cannot be assigned to List<Number>. Learn how this design prevents type safety issues such as ClassCastException when adding incompatible objects to collections.

We'll cover the following...
1.

What is type erasure?

Show Answer
Did you find this helpful?
Java
import java.util.*;
class Demonstration {
public static void main( String args[] ) {
// Raw type
ArrayList al = new ArrayList();
// ArrayList of Strings
ArrayList<String> strs = new ArrayList<>();
// ArrayList of ArrayList of Strings
ArrayList<ArrayList<String>> lstOfStringLsts = new ArrayList<>();
System.out.println("al.getClass().equals(strs.getClass()) = " + al.getClass().equals(strs.getClass()));
System.out.println("al.getClass().equals(lstOfStringLsts.getClass()) = " + al.getClass().equals(lstOfStringLsts.getClass()));
}
}
1.

Can you give examples of type erasure?

Show Answer
1 / 4
Java
import java.util.*;
class Demonstration {
public static void main( String args[] ) {
}
<T extends List<Integer>> void print(T lst) {
for (Integer i : lst)
System.out.println(i);
}
<T extends List<String>> void print(T lst) {
for (String str : lst)
System.out.println(str);
}
<T extends List> void print(T lst) {
for (Object str : lst)
System.out.println(str);
}
}
1.

What is the difference between C++ template library and Java generics?

Show Answer
1 / 2
Java
import java.util.*;
class Demonstration {
public static void main( String args[] ) {
List<Integer> list = new ArrayList<>();
someMethod(list);
}
/*
* Uncomment the following method and comment out the
* other method to see the compile error generated.
*
*/
/*static void someMethod(List<Number> nums){
// ... method body
}*/
static void someMethod(List<? extends Number> nums){
// ... method body
System.out.println("Comment out this method and uncomment the already commented method to see the compiler error.");
}
}

Consider the following snippet to understand why List<Integer> is ...