Generics: that is, "parameterized type", the data type operated is specified as a parameter. This mechanism allows programmers to detect illegal types at compile time.
The difference between not using generics and using generics
No generic code:
import java.util.ArrayList;import java.util.List;public class NoGenerics {public static void main(String[] args){List arrayList=new ArrayList();arrayList.add("1"); //character type arrayList.add(1); //number type for(int i=0;i<arrayList.size();i++){String s=(String) arrayList.get(i); //Cast conversion, but cannot be converted to character type, and no error was reported for compilation System.out.println(s);}}}Using generic code:
import java.util.ArrayList;import java.util.List;public class Generics {public static void main(String[] args){List<String> stringList = new ArrayList<String>();List<Integer> integerList = new ArrayList<>(); //Simplify stringList.add("1"); //StringList.add(1); //Compile error, only character type can be added integerList.add(1); //IntegerList.add("1"); //Compile error, only number type can be added for(int i=0;i<stringList.size();i++){String s=stringList.get(i);System.out.println(s);}for(int j=0;j<integerList.size();j++){int i=integerList.get(j);System.out.println(i);}}}Note: In the jdk version, List<String> stringList = new ArrayList<String>(); can be abbreviated as List<String> stringList = new ArrayList<>();
Advantages of generics:
1. Type safety; for example, List<String> can only insert String types, simply put it as restricting types.
2. Eliminate casting; make the code more readable and reduce the chance of errors.
3. Potential performance benefits; generics bring possibilities for larger optimizations. If there are no generics, programmers will specify these casts.
Notice:
1. The type parameters of generic types can only be class types (including custom classes), not simple types. For example List<String,Person>
2. There can be multiple type parameters for generics, such as List<String,Integer>