Importance of Java Generics!
Generics are one of the most controversial Java language features. Generics allows a type or method to operate on objects of various types while providing compile-time type safety, making Java a fully statically typed language. Here are five important things to know about Generics
1 .Generics are implemented using type erasure
In Java a class or an interface can be declared to define one or more type parameters and those type parameters should be provided at the time of object construction.
2. Generics does not support sub-typing
Generics does not support sub-typing which means that List is not considered to be a sub-type of List, where S is a subtype of T.
3. You can't create Generic Arrays
Arrays uses this information at runtime to check the type of the object it contains and will throw ArrayStoreException if the type does not match. But with Generics type information gets erased and the array store check will succeed in cases where it should fail.
4. Use of wildcards with extends or super to increase API flexibility
There are times that you need to work not only with T but also with sub types of T. For example, the addAll method in the Collection interface which adds all the elements in the specified collection to the collection on which it is called.
5. Use of Multiple Bounds
Multiple bounds is one of the generics features which most developer do not know. It allows a type variable or wildcard to have multiple bounds. For example, if you to define constraint such as that the type should be a Number and it should implement Comparable.
Problems solved by Java Generics
Prior to java 1.5, there was no way to specify types for objects when we need to use them in collections. Java is supposed to be a typed language and not being able to specify the types of its objects where necesary completely defeats the purpose. Developers find themselves working with a lot of collections and not guaranteeing the type objects contained in their collections exposed their code to potential bugs.