This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021.

Generic is essentially the parameterization of data types.

Cainiao website:

Generics are a new feature introduced in JDK 5. Generics provide compile-time type-safety checks that allow programmers to detect illegal types at compile time.

The declaration location of the generic type, immediately after the class name, is wrapped with <> :

class MyCollection <E> { // Equivalent to formal parameters
    Object[] objects = new Object[5];

    public void set(E e, int index) {
        objects[index] = e;
    }

    public E get(int index) {
        return(E)objects[index]; }}Copy the code

In the code above, generics are used. Inside the class, the set and get methods are a little bit different.

  • The first set method sets the element e at index. The type of e is e. I don’t care what it is. It will be what it is when it is defined. Put a reference to E in the index of the Objects array.
  • The second get method, which returns the element corresponding to an index, returns type E. Return is implemented with a cast.

And the nice thing about this is, you don’t have to decide what type it has to be, so you can see if I changed seventy-two. I can pass basic data types, or I can pass more complicated ones, define a class. It’s very flexible. It’s a Java wow moment.

code

Write a test for main() based on the above definition.

After the first line is typed, then set, IDEA will be intimate prompt:The type of parameter in the set method is the same as that in the first sentenceMyCollection<>Angle brackets here have the same type.

public class TestGeneric {
    public static void main(String[] args) {
        MyCollection<String> mc = new MyCollection<>(); // Equivalent to the actual parameter
        mc.set("fang".0);
        mc.set("Kris".2);

        String b = mc.get(2);
        System.out.println("Element 3:" + b);
//
// List list = new ArrayList();
// Map map = new HashMap();}}Copy the code

Running results:

Combine some method overrides, such as the Comparable method, and you can implement custom comparisons.

In Python, if a function is passing an argument, you don’t need to specify the type. Implicitly, the generic approach is implemented.

In advanced versions, hints have been added. For example, when LeetCode defines a function, the type of num in parentheses is int.

Help my Moment

Map.get (index); After that, I want this to print itself out. Println is wrapped in system.out.println.

Every time I see the result, I’m like, oh, I didn’t print anything. Only in this way can we turn around and correct ourselves.

If a master has a similar psychology, ask for advice ~