Hello, today for you to share Java generics, quickly take out a small book to write it down!
What are generics
1. Background:
Before The introduction of generics in JAVA, a programmer could build a collection of elements of type Object, which could store any data type Object. When using this collection, the programmer needed to know exactly what data type to store each element, otherwise it was easy to throw a ClassCastException. Here’s an example
public class demo {
public static void main(String[] args) { ArrayList list = new ArrayList(); list.add("java"); list.add(132); list.add(true); for (int i = 0; i < list.size(); i++) { Object o = list.get(i); String str = (String)o; System.out.println(str); }}Copy the code
}
An error will be reported after running
An Integer cannot be converted to a String. This is not a compilation error, but a runtime error.
2. The concept:
Java Generics is a new feature introduced in JDK5 that provides a compile-time type safety monitoring mechanism that allows us to detect illegal type data structures at compile time. The nature of generics is parameterized types, where the data type being operated on is specified as a parameter.
3. Benefits:
Check types at compile time
Cast type conversions are eliminated
As shown in figure
Both int and Boolean types return an error
ArrayList list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
for (int i = 0; i < list1.size(); i++) {
String str = list1.get(i);
System.out.println(str);
}
Copy the code
The run result is
Type casting is eliminated
2. Generic classes, interfaces
1. A generic class
(1) Use grammar
Class name < concrete data type > object name = new Class name < concrete data type >();
(2) after Java1.7, specific data types in <> can be omitted
Class name < concrete data type > object name = new class name <>(); Diamond grammar
2. Generic classes:
Generic classes, in which case the operation type is Object if no specific data type is specified.
The type parameters of a generic type can only be class types, not basic data types, because when compiled, the class will be treated as Object. The basic data types do not inherit from Object, so they cannot be used as basic data types.
A generic type can be logically thought of as a number of different types, but in reality they are all the same type
This can be understood in conjunction with Generic erasure, after which Generic< String > and Generic< Integer > are Generic classes.
A generic class:
The test class:
Print the result
3. Derive subclasses from generic classes
- A subclass is also a generic class, and the subclass must have the same generic type as its parent
- A subclass is not a generic class. The parent class specifies a generic type
4. Generic interfaces
Definition syntax for generic interfaces
Interface Interface name < generic id, generic ID,… > {
Generic identification method name (); .Copy the code
}
5. Use of generic interfaces
- The implementation class is also a generic class, and the generic type of the implementation class and interface should be the same
Implementation classes are not generic classes, and interfaces are explicitly typed
/ * *
- Classes that implement generic interfaces, not generic classes, need to specify the data type that implements the generic interface.
* /
public class Apple implements Generator {
@Override
public String getKey() {
return "hello generic";
}
Copy the code
}
Generic methods
Use 1.
A generic method specifies the specific type of the generic when the method is called.
2. Grammar:
// <T, E,… > Return value type method name (parameter list) {method body… }
public <T> void Getkey(ArrayList<T> key_list){
}
Copy the code
3. Specification:
The distinction between public and return value is very important, which can be interpreted as declaring this method generic.
Only declared methods are generic. Member methods that use generics in a generic class are not generic.
< T > indicates that the method will use the generic type T before you can use the generic type T in the method.
As with the definition of generic classes, T can be written as an arbitrary identifier, and common parameters such as T, E, K, and V are often used to represent generics.
4. Generic methods and mutable parameters
public class Test {
public <E> void print(E... e){ for (int i=0; i<e.length; i++){ System.out.println(e[i]); }}Copy the code
}
public class demo {
public static void main(String[] args) { Test test = new Test(); The test print (1, 2, 3); test.print("a","b","c"); }Copy the code
}
Print the result
5. Summary of generic methods
-
Generic methods allow methods to change independently of classes
-
If a static method is to use generic capabilities, it must be made generic
/ * *
* Static generic methods, * @param t * @param e * @param k * @param < t > * @param < e > * @param < k > */ public static < t, e, k > void printType(T t, E e, K k) { System.out.println(t + "\t" + t.getClass().getSimpleName()); System.out.println(e + "\t" + e.getClass().getSimpleName()); System.out.println(k + "\t" + k.getClass().getSimpleName()); }Copy the code
4. Type wildcard
1. What is a type wildcard
The type wildcard is usually “?” Instead of a concrete type argument.
public static void showBox(Test<? > test){
System.out.println(test.getKey());
}
Copy the code
Therefore, type wildcards are type arguments, not type parameters.
2. Upper limit of type wildcards
Grammar:
Class/interface <? Extends argument type >
public static void showBox(Test<? extends Number> test){
System.out.println(test.getKey());
}
Copy the code
The type of the generic type required can only be an argument type, or a subclass of the argument type.
3. Lower limit of type wildcards
Grammar:
// class/interface <? Super argument type >
public static void showBox(Test<? super Integer> test){
System.out.println(test.getKey());
}
Copy the code
The type of the generic type required can only be an argument type or a parent of the argument type.
Fifth, type erasure
1. The concept
Generics were introduced in Java version 1.5. Before that, there were no generics, but generics code was perfectly compatible with previous versions of code. That’s because generics information only exists during code compilation, and before entering the JVM, generic-related information is erased, which we call — type erasure.
2. The classification:
- Unrestricted type erasure
- There are limited types of erasure
- Erases parameters defined by the type in the method
- The bridge method
Generics and arrays
- Generic array creation can declare array references with generics, but cannot create array objects with generics directly
// Wrong way
ArrayList[] listArr = new ArrayList<5>();
// The correct way
ArrayList[] list = new ArrayList[5];
ArrayList[] listArr = list;
/ / or
ArrayList[] listArr = new ArrayList[5];
- Arrays of T[] can be created using newInstance(Class,int) of java.lang.reflect.Array
public class Fruit {
private T[] array; Public Fruit(Class<T> CLZ, int length){array.newinstance = (T[]) array.newinstance (CLZ, length); }Copy the code
}
Well, that’s all for today’s article, hoping to help those of you who are confused in front of the screen