1. A Method without Generic Type
Assuming you want to write a method that takes two sets and get their intersection. Here is one way to write such a method:
public static Set getIntersection(Set set1, Set set2){ Set result = new HashSet(); for(Object o: set1){ if(set2.contains(o)) result.add(o); } return result; } |
This method is not type-safe and the compiler gives warnings. It has several potential problems. First, when the method is called and some set is returned, the caller may not know the type and need a cast operation for each element. Second, two sets with different types should not be able to be passed to the method. Last and in general, we should alway fix the warning messages.
2. A Method with Generic Type
The method can be fixed by specifying a generic type like the following:
public static <E> Set<E> getIntersection(Set<E> set1, Set<E> set2){ Set<E> result = new HashSet<E>(); for(E o: set1){ if(set2.contains(o)) result.add(o); } return result; } |
This method is type-safe and there are no warnings. We specify the element type of the three sets should be the same E. In this way, the caller knows the return type, so it can directly use its element without casting. There is now strict restrictions on the element type, so only two sets with the same element type can get the intersection.
Note that the type parameter list, <E>
in this case, goes between the method’s modifiers and its return type.