Generics are known for their type safety, which is obviously a good thing. However, it has a flip side. As we’ve already discussed, type erasure — the compiler process that preserves type safety — can complicate program logic. Now it’s time to discuss another generics-related notion: reification.
Generics were introduced to implement generic programming and control type-safety at compile-time. The feature has been available since Java 5. To support backward compatibility with previous Java versions, information about generic types is erased by the compiler. We will cover exactly which types are erased in future topics.
Earlier, when we were discussing type bounds, we mentioned Wildcards as a feature that serves a similar purpose and has wide application.
Introduction In previous articles, we have mentioned that generics can accept any type of parameter and make it possible to reuse some code. Let’s now consider an example that will reveal another aspect of generics. Imagine that we have a generic Storage<T> class that can contain objects of any class. But there are some situations when we want to restrict these objects. We can say, for example,…
In previous topics we have discussed generic classes and how one can use them. But Java also has generic methods that can be very useful. Generic methods allow type parameters to be passed to a method and used in its logic. They also allow a type parameter to be the return type.
As you know, generics enable us to parameterize types when defining classes (or interfaces) and methods. Parameterized types make it possible to re-use the same code while processing different concrete types.
Generic programming There are situations when methods and classes do not depend on the data types on which they operate. For example, the algorithm to find an element in an array can process arrays of strings, integers or custom classes. It does not matter what the array stores: the algorithm is always the same. Yet we cannot write this algorithm as a single method, because…
To detect and memorize whether extends or super should be used it is worth remembering the Get and Put principle: