Type Erasure - Java does not keep record all versions of LinkedList<T>
as separate types.
i.e. We cannot check like this:
if (s instanceof LinkedList<String> ) { ... }
At runtime, all type variables are promoted to Object.
LinkedList<T>
becomes LinkedList<Object>
.Or the Upper Bound, if one is available
LinkedList<? extends Shape>
becomes LinkedList<Shape>
So since no information of T
is preserved, we cannot use T
in expressions like: if (o instanceof T) {...}
What does type erasure mean for us??
Type erasure now means that the code which implements a comparison below always returns True.
o1 = new LinkedList<Employee>();
o2 = new LinkedList<Date>();
if(o1.getClass() == o2.getClass()){
//True -> this block is executed always.
}
Now as a consequence of this, the following overloading is illegal!!
public class Example{
public void printlist(LinkedList<String> strList){ ... }
public void printlist(LinkedList<Date> datelist){ ... }
}
Now, during type erasure, all types variables are promoted to Object
. (Look Here)
So, the basic(primitive) types like int
, float
, … are not compatible with Object
LinkedList<T>
as LinkedList<int>
, LinkedList<double>
,…So Java provides Wrapper classes for each basic types:
Basic Type | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
Basic Type | Wrapper Class |
---|---|
float | Float |
double | Double |
boolean | Boolean |
char | Character |
<aside> 💡 All wrapper classes other than Boolean and Character extend the class Number.
</aside>
Converting from basic type to wrapper class and back:
int x = 5;
Integer myx = Integer(x);
int y = myx.intValue();
Autoboxing - implicit conversion between base types and their wrapper types.
int x = 5;
Integer myx = x;
int y = myx;
<aside> 💡 Use Wrapper types in generic functions.
</aside>