Generics in Java
Quick review.
With generics we can write classes and methods that aren’t tied to just one type. The type of data is specified as a parameter, which must be a reference type, and it’s also possible to restrict it (for example, class Something<T extends Number>).
The main benefits of generics are code reusability (obviously), but also type safety:
Before generics was introduced (JDK 5), you could have used the root class Object as the type for a class member, thus not limiting it to one type for the client. But that wouldn’t be type safe.
Others could cast your object to whatever they want, and cause an error that would be discovered only at runtime (remember, the compiler doesn’t know anything about the type of data in this case).
With generics, all casts are automatic, and we also get type safety.
How is this implemented? with type erasure. The Java compiler doesn’t create different versions our generic class for each type T.
Instead, it substitutes the generic types with their bound types and creates appropriate casts where needed, in a process called erasure. For example, class Data<T extends Number>{ T num } is replaced by class Data{ Number num } . T was replaced by its bounding type.
Notice that this process also enables backwards compatibility with older versions of Java.
Get Mika Tal’s stories in your inbox
Join Medium for free to get updates from this writer.
On the other hand, I can’t write something like this:
ArrayList<Integer> list = new ArrayList<>();// won't compile
System.out.println(list instanceof ArrayList<Integer>);// but this is true
System.out.println(list instanceof ArrayList);
Whereas in C#, generics is implemented differently, so this works:
Console.WriteLine(new List<string>() is List<string>);
// that's fine in C#Appendix: simple example of type safety (Java):
class Something{
Object obj;
}
class SomethingGeneric<T extends Number>{
T t;
}// somewhere else in the code:Something s = new Something();
s.obj = 1;
String str1 = (String) s.obj; // ClassCastExceptionSomethingGeneric<Integer> gen = new SomethingGeneric<>();
gen.t = 2;
String str2 = (String) gen.t; // won't compile
gen.t = "2"; // won't compile









