The use of generic types in java

1. Why do you need generics

Generics can make the program avoid java.lang.ClassCastException at runtime , and make the program writing more standardized;

 

List list = new ArrayList();  
list.add("CSDN_SEU_Cavin");  
list.add(100);  
for (int i = 0; i < list.size(); i++) {  
  String name = (String) list.get(i); //When the Integer is taken out, an exception occurs at runtime  
System.out.println("name:" + name);  
}

// code after importing generics
List<String> list = new ArrayList<String>();  
list.add("CSDN_SEU_Cavin");  
list.add(100); will report an error when compiling

 Second, the type is only valid at the compile stage

 

     During the compilation process, after the generic result is correctly checked, the relevant information of the generic will be erased, and the method of type checking and type conversion will be added at the boundary of the object entering and leaving the method. That is to say, the successfully compiled class file does not contain any generic information. Generic information does not enter the runtime phase.

The benefits of generics

(1) Type safety. 

By knowing the type constraints of variables defined using generics, the compiler can improve the type safety of Java programs more efficiently. 

(2) Eliminate forced type conversion. 

Eliminate many casts in source code. This makes the code more readable and reduces the chance of errors. All casts are automatic and implicit.

(3) Improve performance.

Fourth, the use of generics matters needing attention

(1) The type parameters of generics can only be class types (including custom classes), not simple types.

(2) There can be more than one type parameter of a generic type.

(3) The instanceof operation cannot be used on the exact generic type.

(4) An array of an exact generic type cannot be created

Guess you like

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