Concept and usage scenario of java generics

1, Overview of generics

Generic: a feature introduced in JDK5. It provides a compile time type safety detection mechanism that allows illegal types to be detected at compile time. Its essence is a parameterized type, that is, the operated data type 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

2, Benefits of generics

1. Advance the run-time problem to compile time
2. Casts are avoided

3, Generic definition format

1. < type >: Specifies the format of a type. The type here can be regarded as a formal parameter.
2. < type 1, type 2,... >: Specify mu lt iple types of formats separated by commas. The type here can be regarded as a formal parameter.
3. In the future, the given type can be regarded as an argument, and the type of the argument can only be a reference data type.

4, Generic application scenarios

Generic class

Define format:

Format: modifier class class name < type > {}
Example: public class Generic {}
Here, T can be written as any identifier. Common parameters such as T, E, K and V are often used to represent generics. As shown in the figure:

public class Generic<T>{
	private T t;
	public T getT(){
		return t;
	}
	public void setT(T t){
		this.t=t;
	}
}

generic method

Define format:

Format: modifier < type > return value type method name (type variable name) {}
Example: public void show (T) {}

public class Generic{
	public<T>void show(T t) {
		system.out.println(t);
	}
}

The type can only be confirmed when the method is called.

generic interface

Define format:
Format: modifier interface interface name < type > {}
Example: public interface Generic {}

public interface Generic<T>{
	void show( T t);
}

Interface implementation class

public class GenericImpl<T>implements Generic<T> {
	@Override
	public void show(T t) {
		system.out.println(t) ;
	}
}

5, Type wildcard

Role of type wildcards

  • To represent the parent classes of various generic lists, you can use type wildcards

Type wildcard classification

  • Type wildcard: <? >
  • List<?>: Represents a list whose element type is unknown, and 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 wildcards

  • Upper limit of type wildcard: <? Extensions type >
  • List<? Extensions Number >: the type it represents is Number or its subtype

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

Example code:

public class GenericDemo {
    public static void main(String[] args) {
        //Type wildcard: <? >
        List<?> list1 = new ArrayList<Object>();
        List<?> list2 = new ArrayList<Number>();
        List<?> list3 = new ArrayList<Integer>();
        System.out.println("--------");

        //Upper limit of type wildcard: <? Extensions type >
//Error: List <? extends Number> list4 = new ArrayList<Object>();
        List<? extends Number> list5 = new ArrayList<Number>();
        List<? extends Number> list6 = new ArrayList<Integer>();
        System.out.println("--------");

        //Type wildcard lower limit: <? Super type >
        List<? super Number> list7 = new ArrayList<Object>();
        List<? super Number> list8 = new ArrayList<Number>();
//Error: List <? super Number> list9 = new ArrayList<Integer>();

    }
}

6, Variable parameters

Basic concepts of variable parameters

  • Introduction to 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

  • Variable parameter definition format

    Modifier return value type method name(Data type... Variable name) {  }
    
  • Precautions for variable parameters

    The variable here is actually an array

    If a method has multiple parameters, including variable parameters, the variable parameters should be placed last

  • Basic use of variable parameters

Example code:

public class ArgsDemo01 {
    public static void main(String[] args) {
        System.out.println(sum(10, 20));
        System.out.println(sum(10, 20, 30));
        System.out.println(sum(10, 20, 30, 40));
    }
//If there are multiple parameters and variable parameters are included, the variable parameters shall be placed last
//    public static int sum(int b,int... a) {
//        return 0;
//    }

    public static int sum(int... a) {
        int sum = 0;
        for(int i : a) {
            sum += i;
        }
        return sum;
    }
}

Use of variable parameters

There is a static method in the Arrays tool class:

 public static <T> List<T> asList(T... a)
  • Returns a list of fixed sizes supported by the specified array
  • The returned collection cannot be added or deleted, but can be modified

There is a static method in the List interface:

public static <E> List<E> of(E... elements)
  • : returns an immutable list containing any number of elements
  • The returned collection cannot be added, deleted or modified

There is a static method in the Set interface:

public static <E> Set<E> of(E... elements)
  • Returns an immutable collection containing any number of elements
  • When giving elements, you cannot give duplicate elements
  • The returned collection cannot be added or deleted. There is no modified method

Example code:

public class ArgsDemo02 {
    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> list = Arrays.asList("hello", "world", "java");
//
        list.add("javaee"); //UnsupportedOperationException
        list.remove("world"); //UnsupportedOperationException
//        list.set(1,"javaee");
//
//        System.out.println(list);

        //Public static < E > List < E > of (E... Elements): returns an immutable list containing any number of elements
//        List<String> list = List.of("hello", "world", "java", "world");
//
        list.add("javaee");//UnsupportedOperationException
        list.remove("java");//UnsupportedOperationException
        list.set(1,"javaee");//UnsupportedOperationException
//
//        System.out.println(list);

        //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"); //IllegalArgumentException
        //Set<String> set = Set.of("hello", "world", "java");

//        set.add("javaee");//UnsupportedOperationException
//        set.remove("world");//UnsupportedOperationException

        //System.out.println(set);
    }
}

Keywords: Java

Added by peDey on Tue, 21 Dec 2021 21:21:12 +0200