Skip to content

Instantly share code, notes, and snippets.

@darrenbkl
Created January 16, 2020 15:01
Show Gist options
  • Save darrenbkl/2f64727c74d63959280943d72b4c5f0c to your computer and use it in GitHub Desktop.
Save darrenbkl/2f64727c74d63959280943d72b4c5f0c to your computer and use it in GitHub Desktop.
myList = new ArrayList(); // create a raw type
myList.add(“someString”):
String str = (String) myList.get(0); // someString
Integer i = (Integer) myList.get(0); // error: java.lang.ClassCastException
```
Lots of casting, not very type-safe huh, you would end up with a ClassCastException if you’re not careful.
When JCP introduced generics in Java 5, they have to make sure full backward compatibility with this kind of non-generic code. So, type erasure was introduced.
## Type Erasure
When you write code that made use of generics
```
List<String> myList = new ArrayList<>();
myList.add("filthy frank");
String s = myList.get(0);
```
It gets compiled to
```
List myList = new ArrayList();
myList.add(“filthy frank”):
String s = (String) myList.get(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment