Generic class learning experience

Generic class learning experience


If there is a class Holder used to wrap a variable, the type of the variable may be arbitrary, how to write the Holder? This was possible before generics:





In Holder1, there is a variable referenced by Object. Because any type can be upcast to Object, this Holder can accept any type. When taking it out, the Holder only knows that it saves an Object object, so it needs to be cast to the corresponding type. In the main method, holder1 first saves a string, which is a String object, and then changes to save an Integer object (parameter 1 will be automatically boxed). Coercion is already troublesome when taking variables out of the Holder, but remember different types here, and if you turn it wrong, a runtime exception will occur.
Let's take a look at the generic version of Holder:





In Holder2, the variable a is a parameterized type T, T is just an identifier, and other letters are also possible. When the Holder2 object is created, the type of the parameter T is passed in the angle brackets, then in this object, all occurrences of T are equivalent to being replaced with String. Now the get is not an Object, but a String object, so there is no need for type conversion. In addition, when calling set, only String type can be passed in, otherwise the compilation will fail. This ensures type safety in holder2 and avoids accidentally passing in the wrong type.
From the above example, we can see that pan makes the code easier and safer. After the introduction of generics, some classes in the Java library, such as common container classes, have also been rewritten to support generics. When we use them, we will pass in parameter types, such as: ArrayList<Integer> list = ArrayList<>();.

Generic methods

Generics can not only target classes, but also make a method generic by itself. For example:





The GenericMethod class itself is not generic, and it is not necessary to pass generic parameters when creating its object, but its method f is a generic method. Before the return type is its parameter identifier <K, V>. Note that there are two generic parameters, so there can be multiple generic parameters.

When calling a generic method, you can not explicitly pass in the generic parameter, the above call does not. This is because the compiler uses parameter type inference to infer the types of K and V based on the types of the passed arguments (integer and String in this case).


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326518418&siteId=291194637