- The Collection classes use the Object type to permit different input and return types. We need to cast down explicitly to retrieve the object we need. This is not type safe.
- Although the existing collections frame does support homogeneous collections (that is collections of one of the type object, for example Date objects), there was no mechanism to prevent the other object types from be inserted into the collection.
- Also retrieval almost always required a cast.
- The solution for this problem is to make a use of generics functionality. This was introduced in java SE 5.0 platform.
- It produces information for the compiler about the type of collection used. Hence, type checking is resolved automatically at run time.
- This eliminates the explicit casting of the data types to be used in the collection.
- With the addition of autoboxing of primitive types, we can use generics to write simpler and more understandable code.
Before use the generics, code may look like the following code,
ArrayList list = new ArrayList();
int total = ((Integer)list.get(0)).intValue();
- In above code, we need an Integer wrapper class for type casting while retrieving the integer value from the list.
- At runtime the program needs the type checking for the list.
- With the application generics, the ArrayList should be declared as ArrayList<Integer>, inform the compiler of the type of collection to be used.
- When retrieving the value, there is no need for an Integer wrapper class. The use of generics for the original code is shown as follows,
ArrayList<Integer> list = new ArrayList<Integr>();
int total = list.get(0).intValue();
- The autoboxing facility fits well with the Generics API. Using autoboxing, the code example could be written as a code below,
ArrayList<Integer> list = new ArrayList<Integer>();
int total list.get(0);
- Above code uses the generic declaration and instantiation to declare and instantiate an ArrayList instance of Integer objects.
- Consequently, the addition of a non-Integer type to array generates a compilation error.
Generics are enabled by default since the Java SE 5.0 platform. We can disable generics by using the –source 1.4 option on the javac command.
Generic Set Example:-
- In the following example, the program declares a variable (set) of type Set<String> and assigns it to a new HashSet<String> object.
- It then adds a few String elements and prints the set to the standard output. Line 10 causes a compilation error (because an Integer is not a String).
- The code given below shows the Set implementation using generics. This can be compared to the non-generic Set implementation.
- import java.util.*;
- public class GenSet
- public static void main(String args)
- Set<String> set = new HashSet<String>();
- // this line generates compile error
- set.add(new Integer(4));
- // duplicate is not added