The importance of generics in Java
This article will explain in detail the importance of generics in the Java language. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
1. There are no methods of generic types
Suppose you want to write a method that requires two sets and obtains the intersection of them. This is one way to write such methods:
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 a warning. It has several potential problems. First, when the method is called and some collections are returned, the caller may not know the type and need to cast each element. Second, you cannot pass two different types of collections to a method. Finally, in general, we should always fix warning messages.
two。 Generic method
This method can be fixed by specifying a generic type, as follows:
Public static Set getIntersection (Set set1, Set set2) {Set result = new HashSet (); for (E o: set1) {if (set2.contains (o)) result.add (o);} return result;}
This method is type-safe with no warning. We specify that the element type of the three collections should be the same E. In this way, the caller knows the return type, so its elements can be used directly without casting. There are now strict restrictions on element types, so only collections of the same element type can be intersected.
Note that in this case, the list of type parameters is between the modifier of the method and its return type.
This is the end of this article on the importance of generics in the Java language. I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.