JAVA07--Generic

Java generics is a new feature introduced in JDK 5. Generics provides a compile-time type safety detection mechanism, which allows programmers to detect illegal types at compile time.
The essence of generics is the parameterized type, which means that the data type being operated on is specified as a parameter.
Rules for defining generic methods:

  • All generic method declarations have a type parameter declaration section (separated by angle brackets) that precedes the method return type (in the example below).
  • Each type parameter declaration contains one or more type parameters, separated by commas. A generic parameter, also known as a type variable, is an identifier used to specify a generic type name.
  • The type parameter can be used to declare the return value type, and can be used as a placeholder for the actual parameter type obtained by the generic method.
  • The declaration of the generic method body is the same as other methods. Note that type parameters can only represent reference types, not primitive types (like int, double, char, etc.).

The following example demonstrates how to use generic methods to print elements of different strings:

public class GenericMethodTest
{
   // 泛型方法 printArray                         
   public static < E > void printArray( E[] inputArray )
   {
      // 输出数组元素            
         for ( E element : inputArray ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }
 
    public static void main( String args[] )
    {
        // 创建不同类型数组: Integer, Double 和 Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
 
        System.out.println( "整型数组元素为:" );
        printArray( intArray  ); // 传递一个整型数组
 
        System.out.println( "\n双精度型数组元素为:" );
        printArray( doubleArray ); // 传递一个双精度型数组
 
        System.out.println( "\n字符型数组元素为:" );
        printArray( charArray ); // 传递一个字符型数组
    } 
}

Compile the above code, the running result is as follows:
integer array elements are:
1 2 3 4 5

The elements of the double array are:
1.1 2.2 3.3 4.4

Character array elements are:
HELLO

Bounded type parameters:
Sometimes, you may want to limit the range of types that are allowed to be passed to a type parameter. For example, a method for manipulating numbers may only wish to accept instances of Number or Number subclasses. This is the purpose of bounded type parameters.
To declare a bounded type parameter, first list the name of the type parameter, followed by the extends keyword, and finally its upper bound.
Examples
The following examples demonstrate how "extends" can be used in the general sense of "extends" (classes) or "implements" (interfaces). The generic method in this example returns the maximum of three comparable objects.

public class MaximumTest
{
   // 比较三个值并返回最大值
   public static <T extends Comparable<T>> T maximum(T x, T y, T z)
   {                     
      T max = x; // 假设x是初始最大值
      if ( y.compareTo( max ) > 0 ){
         max = y; //y 更大
      }
      if ( z.compareTo( max ) > 0 ){
         max = z; // 现在 z 更大           
      }
      return max; // 返回最大对象
   }
   public static void main( String args[] )
   {
      System.out.printf( "%d, %d 和 %d 中最大的数为 %d\n\n",
                   3, 4, 5, maximum( 3, 4, 5 ) );
 
      System.out.printf( "%.1f, %.1f 和 %.1f 中最大的数为 %.1f\n\n",
                   6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
 
      System.out.printf( "%s, %s 和 %s 中最大的数为 %s\n","pear",
         "apple", "orange", maximum( "pear", "apple", "orange" ) );
   }
}

Compile the above code, the results are as follows:

The largest number among 3, 4 and 5 is 5

The largest number among 6.6, 8.8 and 7.7 is 8.8

The largest number in pear, apple and orange is pear

Generic class

Generic class declarations are similar to non-generic class declarations, except that a type parameter declaration section is added after the class name.
Like the generic method, the type parameter declaration part of the generic class also contains one or more type parameters, separated by commas. A generic parameter, also known as a type variable, is an identifier used to specify a generic type name. Because they accept one or more parameters, these classes are called parameterized classes or parameterized types.

Examples The
following examples demonstrate how we define a generic class:

public class Box<T> {
   
  private T t;
 
  public void add(T t) {
    this.t = t;
  }
 
  public T get() {
    return t;
  }
 
  public static void main(String[] args) {
    Box<Integer> integerBox = new Box<Integer>();
    Box<String> stringBox = new Box<String>();
 
    integerBox.add(new Integer(10));
    stringBox.add(new String("人生苦短"));
 
    System.out.printf("整型值为 :%d\n\n", integerBox.get());
    System.out.printf("字符串为 :%s\n", stringBox.get());
  }
}

Compile the above code, the running result is as follows: The
integer value is: 10

The string is: Life is short

Type wildcard

1. Type wildcards generally use? Instead of specific type parameters. For example, List <?> Is logically the parent class of all List <concrete type arguments> such as List and List.

import java.util.*;
 
public class GenericTest {
     
    public static void main(String[] args) {
        List<String> name = new ArrayList<String>();
        List<Integer> age = new ArrayList<Integer>();
        List<Number> number = new ArrayList<Number>();
        
        name.add("icon");
        age.add(18);
        number.add(314);
 
        getData(name);
        getData(age);
        getData(number);
       
   }
 
   public static void getData(List<?> data) {
      System.out.println("data :" + data.get(0));
   }
}

The output is:

data :icon
data :18
data :314

Analysis: Because the parameters of the getData () method are of type List, name, age, number can be used as the actual parameters of this method, this is the role of wildcards

2. The upper limit of the type wildcard is defined by a list, such a definition is that the wildcard generic value accepts Number and its subclass types.

import java.util.*;
 
public class GenericTest {
     
    public static void main(String[] args) {
        List<String> name = new ArrayList<String>();
        List<Integer> age = new ArrayList<Integer>();
        List<Number> number = new ArrayList<Number>();
        
        name.add("icon");
        age.add(18);
        number.add(314);
 
        //getUperNumber(name);//1
        getUperNumber(age);//2
        getUperNumber(number);//3
       
   }
 
   public static void getData(List<?> data) {
      System.out.println("data :" + data.get(0));
   }
   
   public static void getUperNumber(List<? extends Number> data) {
          System.out.println("data :" + data.get(0));
       }
}

Output result:

date: 18
date: 314

Published 23 original articles · praised 7 · 1002 views

Guess you like

Origin blog.csdn.net/qq_34356768/article/details/105185284