-
-
Save darrenbkl/2f64727c74d63959280943d72b4c5f0c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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