Basic Java learning notes 21 - generics

Posted by davidprogramer on Thu, 06 Jan 2022 12:09:14 +0100

catalogue

1. Generic overview

1.1 definition format of generic type

1.2 benefits of generics

2. Generic class

2.1 definition format of generic class

2.2 code demonstration of generic classes

3. Generic method

3.1 definition format of generic method

3.2 code demonstration of generic methods

4. Generic interface

4.1 definition format of generic interface

4.2 code demonstration of generic interface

5. Type wildcard

6. Variable parameters

6.1 use of variable parameters

1. Generic overview

Generic time is a feature introduced in JDK5, which provides a compile time type safety detection mechanism, which allows illegal types to be detected at compile time. Its essence is parameterized type, that is, the data type operated is specified as a parameter.

When referring to parameters, the most familiar thing is that there is a formal parameter when defining the method, and then the arguments are passed when the method is called. So what about parameterized types?

As the name suggests, it is to parameterize the type from the original specific type, and then pass in the specific type when using / calling. This parameter type can be used in classes, methods and interfaces, which are called generic classes, generic methods and generic interfaces respectively.

1.1 definition format of generic type

//Generic definition format
<type> : Specify a type of format. The type here can be regarded as a formal parameter
<Type 1,Type 2,...> : Specify multiple types of formats separated by commas. The type here can be regarded as a formal parameter
 In the future, when a specific call is made, the given type can be regarded as an argument, and the type of the argument can only be a reference data type.

1.2 benefits of generics

  • Advance the run-time problems to the compilation time;
  • Cast is avoided.

2. Generic class

2.1 definition format of generic class

Formats: modifiers class Class name<type> {}
example: public class Generic<T> {}
//Here, T can be written as any identifier. Common parameters such as T, E, K and V are often used to represent generics

2.2 code demonstration of generic classes

package GPackage;

//Generic class
public class Generic<T> {
    private T t; //Type T as a parameter

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}
package GPackage;

public class Test {
    public static void main(String[] args) {
        Generic<String> g1 = new Generic<String>();
        g1.setT("Zhang San");
        System.out.println(g1.getT());

        Generic<Integer> g2 = new Generic<Integer>();
        g2.setT(20);
        System.out.println(g2.getT());
    }
}
result:
Zhang San
20

3. Generic method

3.1 definition format of generic method

Formats: modifiers <type> Return value type method name (type variable name){}
example: public <T> void show(T t){}

3.2 code demonstration of generic methods

package GPackage;

//Class
public class Generic {
    public <T> void show(T t){
        System.out.println(t);
    }
}
package GPackage;

public class Test {
    public static void main(String[] args) {
        Generic g = new Generic();
        g.show("Zhang San");
        g.show(20);
    }
}
result:
Zhang San
20

4. Generic interface

4.1 definition format of generic interface

Formats: modifiers interface Interface name<type> {}
example: public interface Generic<T> {}

4.2 code demonstration of generic interface

package GPackage;

//generic interface 
public interface Generic<T> {
    void show(T t);
}
package GPackage;

//Implementation class of generic interface
public class GenericImpl<T> implements Generic<T>{
    @Override
    public void show(T t) {
        System.out.println(t);
    }
}
package GPackage;

public class Test {
    public static void main(String[] args) {
        Generic<String> g1 = new GenericImpl<String>();
        g1.show("Zhang San");

        Generic<Integer> g2 = new GenericImpl<Integer>();
        g2.show(20);
    }
}
result:
Zhang San
20

5. Type wildcard

To represent the parent classes of various generic lists, type wildcards can be used.

Type wildcard:<?>
List<?>: Indicates that the element type is unknown List,Its elements can match any type

This List with wildcards only indicates that it is the parent of various generic lists, and cannot add elements to it.

If we don't want List <? > Is the parent class of any generic List. You only want it to represent the parent class of a generic List. You can use the upper limit of type wildcard:

Type wildcard upper limit:<? extends type>
List<? extends Number>: The type it represents is Number Or its subtypes

In addition to specifying the upper limit of type wildcards, we can also specify the lower limit of type wildcards:

Type wildcard lower limit:<? super type>
List<? super Number>: The type it represents is Number Or its parent type

Code demonstration:

package GPackage;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        //Object is the parent of Number and Number is the parent of Integer
        //Type wildcard: <? >
        List<?> list1 = new ArrayList<Object>();
        List<?> list2 = new ArrayList<Number>();
        List<?> list3 = new ArrayList<Integer>();

        //Upper limit of type wildcard: <? Extensions type >
        //List<?  extends Number> list11 = new ArrayList<Object>(); // An error is reported because the upper limit is number
        List<? extends Number> list22 = new ArrayList<Number>();
        List<? extends Number> list33 = new ArrayList<Integer>();

        //Lower limit of type wildcard: <? Super type >
        List<? super Number> list111 = new ArrayList<Object>();
        List<? super Number> list222 = new ArrayList<Number>();
        //List<?  super Number> list333 = new ArrayList<Integer>(); // An error is reported because the lower limit is integer
    }
}

6. Variable parameters

Variable parameters are also called variable number of parameters. If they are used as formal parameters of a method, the number of method parameters is variable.

Format of variable parameters:

Format: modifier return value type method name (data type)... (variable name){}
example: public static int sum(int... a){}

Precautions for variable parameters:

  • The variable a here is actually an array;
  • If a method has multiple parameters and contains variable parameters, the variable parameters should be placed last.

Code demonstration:

package GPackage;

public class Test {
    public static void main(String[] args) {
        System.out.println(sum(1,2));
        System.out.println(sum(1,2,3));
        System.out.println(sum(1,2,3,4));
    }

    //Variable parameters. If there are multiple parameters, the variable parameters should be placed last
    public static int sum(int b, int... a){
        //a is an array of parameters
        int sum = 0;
        for(int i: a){
            sum += i;
        }
        return sum;
    }
}
result:
3
6
10

6.1 use of variable parameters

There is a static method in the Arrays tool class:

//Returns a list of fixed sizes supported by the specified array
public static <T> List<T> asList(T... a){}

The returned collection cannot be added or deleted, but can be modified

There is a static method in the List interface:

//Returns an immutable list containing any number of elements
public static <E> List<E> of(E... elements){}

The returned collection cannot be added, deleted or modified

There is a static method in the Set interface:

//Returns an immutable collection containing any number of elements
public static <E> Set<E> of(E... elements){}

When giving elements, you cannot give duplicate elements
 The returned collection cannot be added or deleted. There is no modified method

Code demonstration:

package GPackage;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class Test {
    public static void main(String[] args) {
        //Public static < T > List < T > aslist (t... A): returns a fixed size list supported by the specified array
        List<String> list1 = Arrays.asList("Hello", "World", "Java");
        System.out.println(list1);
        //list1.add("JavaEE"); // Error: Unsupported operationexception
        //list1.remove("Java"); // Error: Unsupported operationexception
        list1.set(1, "JavaEE"); //No error is reported because the length of the list remains unchanged

        //Public static < E > List < E > of (E... Elements): returns an immutable list containing any number of elements
        List<String> list2 = List.of("Hello","World","Java","World");
        System.out.println(list2);
        //list2.add("JavaEE"); // Error: Unsupported operationexception
        //list2.remove("Java"); // Error: Unsupported operationexception
        //list2.set(1, "JavaEE"); // Error: Unsupported operationexception

        //Public static < E > set < E > of (E... Elements): returns an immutable set containing any number of elements
        //Set<String> set = Set. of("Hello","World","Java","World"); // Error: IllegalArgumentException
        Set<String> set = Set.of("Hello","World","Java");
        System.out.println(set);
        //set.add("JavaEE"); // Error: Unsupported operationexception
        //set.remove("Java"); // Error: Unsupported operationexception
    }
result:
[Hello, World, Java]
[Hello, World, Java, World]
[World, Java, Hello]

Topics: Java Back-end