Simple understanding of Java generics

Advantage 1:

Without using generics, adding a non-string to the list collection will report an error at runtime: type mismatch

ObjectList.java:

1  package cn.nxl2018;
 2  import java.util.ArrayList;
 3  import java.util.List;
 4  public  class ObjectList {
 5      public List getList() {
 6          List list = new ArrayList();
 7          list.add( new Integer (20)); // This sentence will report an error: type mismatch 
8          list.add("b" );
 9          list.add("c" );
 10          return list;
 11      }
 12 }

GenericityDemo.java

 1 package cn.nxl2018;
 2 import java.util.List;
 3 public class GenericityDemo {
 4     public static void main(String[] args) {
 5         // TODO Auto-generated method stub
 6         ObjectList objectList = new ObjectList();
 7         List list=objectList.getList();
 8         String string = (String)list.get(1);
 9         System.out.println(string);
10     }
11 }

Use generics:

If you specify that the data of type String is placed in the list collection, when editing the code, the add() method will automatically report an error indicating that the type does not match (as shown in the figure below). That is to say, when adding an element to the list collection, the compiler will judge whether the data type of the added element is legal according to the parameterized type. If the type is a non-parameterized type, the compiler will give an error message. Under normal circumstances, an exception error will be prompted when the code is running, but it can be prompted when editing, which obviously speeds up the efficiency of our programming.


Advantage 2: When using the get() method to obtain the data in the list without using generics, data conversion is also required, which is troublesome.

1 List list= objectList.getList();
 2 String string = (String)list.get(1); // Convert Object type to String type

If you use generics to specify the type of data to be obtained, then when you use get() to obtain the data in the list, the type of the returned value is directly the specified String type, saving the trouble of converting the original Object type data to String type .

1 List<String>  list=objectList.getList();
2 String string = list.get(0);

Attachment: For the sake of universality, the parameter types in the add() method of the traditional List class are all of the Objext type, and the type of the corresponding get() return value is also of the Object type.

Associated CSDN blog: https://blog.csdn.net/m0_38022608/article/details/80197701

Guess you like

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