Understand generics thoroughly

Because the OOP feature of JAVA is so classic that many OOP languages ​​will learn from it later, I will first borrow the JAVA language to explain the concept of generics. At the end of this article, I will use TypeScript to talk about generics in the front-end field.

Why have generics In the era without generics, various classes must be defined in JAVA and a clear type must be specified for variables. Therefore, coercion is often used when assigning values ​​to variables. This forced conversion does not report an error at compile time, but may throw a ClassCastException at runtime. Let's talk about an example of vividness.

/* JAVA */

public class Bobo{

    class Water{
    }

    class Wine{
    }

    public static void main(String[] args) {
        Bobo bobo= new Bobo();
        Map map = new HashMap();
        map.put("water", bobo.new Water());
        map.put("wine", bobo.new Wine());

        Wine wine = (Wine) map.get("water");
        System.out.println(wine);
    }

}

The meaning of this code is: we put a glass of water (Water) in the map, and put a glass of wine (Wine), when we want to take out the wine from the map, we accidentally take the water out. There is no problem when this code is compiled, but ClassCastException will be reported when it is run (water is not wine after all, otherwise it would be messy?)

This exception may be caused by the programmer's carelessness (it is too easy to make this mistake), but the impact is fatal (the program crashes). So in order to eliminate this anomaly, generics appeared. Of course, this is only one of the important reasons, and more is to make the code in the project more flexible and reusable.

definition The so-called "generic" means "broad data type".

Generics are such a special type-it defers the work of type clarification until the object is created or the method is called. To put it plainly is to provide a higher level of OOP abstraction/flexibility

  • Pass the type as a parameter;
  • This type of parameter can only be used to represent reference types, and cannot be used to represent basic types such as int, double, char, etc. But passing basic types will not report an error, because they will be automatically boxed into corresponding reference types.

JAVA generic design principle: As long as there is no warning during compilation, there will be no ClassCastException exception during runtime.

Generics are actually not limited to specifying a certain type of parameter when defining a class, method, or interface, and let the caller of the class, method, or interface decide which type of parameter to use. For example, the maker of the glass said, I don’t know what the user is doing with this glass, so I am only responsible for making such a glass; the user of the glass said, that’s right, I’ll decide this Is the only glass for water or wine, or rock sugar.

Generic class

Generic class is to define the generic type on the class, when the user uses the class, the type parameter variable is clarified. In this case, the user has clarified what type of parameter variable, and what type the class represents. Users don't need to worry about the conversion exception ClassCastException when using it.

Generic class is to define the generic type on the class, when the user uses the class, the type parameter variable is clarified. In this case, the user has clarified what type of parameter variable, and what type the class represents. Users don't need to worry about the conversion exception ClassCastException when using it.

Which type the user ultimately wants to use, specify the type parameter variable T when creating it. When the class is subsequently used, the class will be automatically converted to the type that the user wants.

/* JAVA */
public static void main(String[] args) {
//Create an object and specify the element type
Bobo<String> c = new Bobo<>();
c.setObj(new String("bobo"));
String s = c.getObj();
System.out.println(s);//>> bobo
//Create an object and specify the element type
Bobo<Integer> cc = new Bobo<>();
/**
* If the String type is passed in this object, it will not pass at compile time.
*/
cc.setObj(10);
int i = cc.getObj();
System.out.println(i);//>> 10
}

2). Generic method A certain method needs to use generics, and the outside world only cares about the method and does not care about other attributes of the class. In this case, if we define generics on the entire class, it would be a little fuss. At this time, we need to use generic methods.

//Define a generic method...
public <T> void show(T t) {
System.out.println(t);
}

What type of parameter variable is passed in by the user, and what type is the return value.

public static void main(string[] args) {
//Create object
   ObjectTool tool = new ObjectTool()

//Call the method, what type of parameter is passed in, and what type of return value is
   tool.show("bobo")
   tool.show("1989")
}

3). Generic interface Generic interfaces can also be defined in Java. I won’t go into details here, just give the sample code:

//Define generic interface
interface Info<T> {
public T getVar();
}
//Implement the interface
class InfoImp<T> implements Info<T> {
private T var;
// Define generic construction method
public InfoImp(T var) {
this.setVar(var);
}
public void setVar(T var) {
this.var = var;
}
public T getVar() {
return this.var;
}
}

Use a question mark? to match any type. ? Difference from T ? And T both represent uncertain types, the difference is that we can operate on T, but right? No, such as the following:

/* JAVA */
// Can
T t = operate();
// Can not
? car = operate();