It turns out that generics are so simple (day 18 of learning Java)

Posted by jakeklem on Mon, 14 Feb 2022 13:16:48 +0100

catalogue

I Overview of generics

II Define and use classes with generics

III Define and use methods with generics

IV Define and use interfaces with generics

V Generic wildcard

I Overview of generics

When we learned about the collection, we all know that any Object can be stored in the collection. As long as the objects are stored in the collection, they will be promoted to Object type. When we take out each Object and perform corresponding operations, we must use type conversion.

//Collection using generics: using generics directly controls the type at compile time, and can only store the data defined by generics
        Collection<String> c2=new ArrayList<String>();
        c2.add("I");
        c2.add("LOVE");
        c2.add("JAVA");
  //c2.add(100);   Compilation error
        //Traverse the elements in the collection, and then operate
        for (String str : c2) {
          System.out.println(str.length());
        }

II Define and use classes with generics

  • Generic type: in fact, it refers to an unknown data type, and its specific data type (reference data type) is determined when it is used
  • Define classes with generics:
Modifier class class name < variables representing generics > {}
E can be any generic type, for example, t can represent
  • Use classes with generics: when creating objects with classes with generics, you need to formulate specific data types of generics
  • Usage scenario: when defining a class, if the formal parameter type of the method in the class cannot be determined, or the formal parameter type of the method and the return value type should be consistent, but the data type is not determined, the class can be defined
public class MyArrayList<E> {
/*
      Usage scenario: when defining a class, if the formal parameter type of the method in the class cannot determine what data type it is,

       Or the formal parameter type of the method should be consistent with the return value type, but the data type is uncertain. At this time, this class can be used

     */
public void method01(E e){
        System.out.println(e);

    }
    public E method02(E e){

        return e;

    }
}


 

public class Demo01 {

    public static void main(String[] args) {
        /*

        Generic type: in fact, it refers to an unknown data type, and its specific data type (reference data type) is determined when it is used
            Define classes with generics:
                Format:
                    public class Class name < generic variable >{

                    }

                    Generic variable: any letter is OK, such as A,B,C,D,E

             API:

                    public class ArrayList<E>{

                        public boolean add(E e){}

                    }

            Use classes with generics: when creating objects with classes with generics, you need to formulate specific data types of generics

         */

        MyArrayList<String> my=new MyArrayList<String>();

        my.method01("hello");

        String str = my.method02("world");

        System.out.println(str);

    }

}

 

III Define and use methods with generics

  • Define methods with generics:
Modifier < variable representing generics > return value type method name (parameter) {}
  • Use methods with generics: call methods with generics to determine the specific data type of generics
  • Usage scenario: when defining a method, the return value type or parameter does not know the specific data type
public class MyArrayList<E> {

    //Use generics defined on classes

    public E method01(E e){

        return e;

    }

    //Define methods with generics

    public <T> void method02(){

    }

    // Define methods with generics

    public <T> void method03(T t){

        System.out.println(t);

    }

    // Define methods with generics

    public <T> T method04(T t){
        return t;

    }

}

 

public class Demo01 {

    public static void main(String[] args) {

        MyArrayList<String> my=new MyArrayList<String>();

        String str = my.method01("hello");

        System.out.println(str);

        my.method03("world");

        Integer i = my.method04(100);

        System.out.println(i);

    }

}

 

IV Define and use interfaces with generics

  • Define interfaces with generics:
  public interface interface name < generic variable > {}
  • Use interfaces with generics:
    • When implementing an interface with an implementation class, determine the specific data type of the generic type of the interface: public class class name implements interface name < specific data type > {}
    • When implementing an interface with an implementation class, the specific data type of the generic type of the interface is not determined. Instead, wait until the implementation class object is created to determine the specific data type of the generic type of the interface

public class class name < generic variable > implements interface name < generic variable > {}

 

public interface MyInterface<T> {

    public abstract void show(T t);
}
public class MyInterface01 implements MyInterface<String>{

    @Override

    public void show(String s) {

        System.out.println(s);

    }

}
public class Demo01 {

    public static void main(String[] args) {

        MyInterface01 my01=new MyInterface01();

        my01.show("hello");

        MyIntreface02<Integer> my02=new MyIntreface02<Integer>();

        my02.show(100);

    }

}

V Generic wildcard

  • Basic use of wildcards: when you don't know what type to use to receive, you can use?,? Indicates an unknown wildcard
public class Demo01 {

    public static void main(String[] args) {

        Collection<String> c1=new ArrayList<String>();

        c1.add("hello");

        c1.add("world");

        Collection<Integer> c2=new ArrayList<Integer>();

        c2.add(10);

        c2.add(20);

        method(c1);

        method(c2);

    }

    //Requirements: define a method. The parameters of the method can accept the above two parameters and traverse them

    //Note: generics are not polymorphic

    public static void method(Collection<?> c){

        Iterator<?> it = c.iterator();

        while(it.hasNext()){

            System.out.println(it.next());

        }

    }

}

 

  • Advanced use of wildcards -- restricted generics
    • Upper limit of generics: type name <? Extensions class > object name} can only receive this type and its subclasses
    • Lower bound of generics: type name <? Super class > object name} can only receive this type and its parent type

Requirements: create teacher class and head teacher class, provide name and age attributes, and both have work methods. Store multiple teacher objects and multiple head teacher objects into two collections. Provide a method that can traverse these two collections at the same time and call the work method.

 

 

Topics: Java Back-end