Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java generics


May 10, 2021 Java


Table of contents


Overview

Generics play an important role in java and are widely used in object-oriented programming and various design patterns.

What is generic? Why use generics?

Generic, or Paramethy Type. W hen it comes to parameters, what is most familiar is the tangible parameter when the method is defined, and then the argument is passed when the method is called. S o how do you understand paramethy types?

As the name implies, the type is parameterized from the original specific type, similar to the variable parameters in the method, at which point the type is also defined as an argument (which can be called a type parameter),

The specific type (type reals) is then passed in when used/called.

The essence of generics is to parameterize types (in the absence of creating new types, the types specifically restricted by generics are controlled by the different types specified by generics). T hat is, during generic use,

The data type of the operation is specified as a parameter, which can be used in classes, interfaces, and methods, and is referred to as generic classes, generic interfaces, and generic methods, respectively.


Characteristics

Generics are only valid during the compilation phase. Look at the code below:

List<String> stringArrayList = new ArrayList<String>();
List<Integer> integerArrayList = new ArrayList<Integer>();

Class classStringArrayList = stringArrayList.getClass();
Class classIntegerArrayList = integerArrayList.getClass();

if(classStringArrayList.equals(classIntegerArrayList)){
    Log.d("泛型测试","类型相同");
}

Output: D/generic test: same type.

The above example proves that the program takes the measure of d)-genericization after compilation. T hat is, generics in Java are only valid during the compilation phase. D uring compilation, when generic results are correctly tested, information about generics is output and methods of type checking and type conversion are added at the boundaries of the object's entry and departure methods. That is, generic information does not enter the runtime phase.

This is summed up in one sentence: generic types can logically be thought of as many different types, and are actually the same basic types.


Generic method

You can write a generic method that can receive different types of parameters when called. Depending on the type of parameter passed to the generic method, the compiler handles each method call appropriately.

Here are the rules that define generic methods:

  • All generic method declarations have a type parameter declaration section (separated by angle brackets), which is declared before the method returns the type (in the following example.
  • Each type parameter declaration section contains one or more type parameters, separated by commas. A generic parameter, also known as a type variable, is an identifier used to specify the name of a generic type.
  • Type parameters can be used to declare return value types and can be placeholders for actual parameter types obtained as generic methods.
  • Generic method body declarations are the same as other methods. Note that type parameters can only represent reference types, not original types (such as int, double, char, etc.).

Instance

The following example shows how to print elements of different strings using generic methods:

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( "Array integerArray contains:" );
        printArray( intArray  ); // 传递一个整型数组

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // 传递一个双精度型数组

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // 传递一个字符型型数组
    } 
}

Compile the above code and the results will look like this:

Array integerArray contains:
1 2 3 4 5 6
 
Array doubleArray contains:
1.1 2.2 3.3 4.4
 
Array characterArray contains:
H E L L O

Type parameters with boundaries:

Sometimes, you may want to limit the range of types that are allowed to pass to a type parameter. F or example, a method that manipulates numbers might only want to accept instances of Number or Number sub-classes. 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 follow its upper bound.

Instance

The following example shows how "extends" can be used in the general sense to mean "extends" or "implements" (interfaces). The generic method in this example returns the maximum value 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( "Max of %d, %d and %d is %d\n\n",
                   3, 4, 5, maximum( 3, 4, 5 ) );
 
      System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
                   6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
 
      System.out.printf( "Max of %s, %s and %s is %s\n","pear",
         "apple", "orange", maximum( "pear", "apple", "orange" ) );
   }
}

Compile the above code and the results will look like this:

Maximum of 3, 4 and 5 is 5
 
Maximum of 6.6, 8.8 and 7.7 is 8.8
 
Maximum of pear, apple and orange is pear

Generic class

The declarations of generic classes are similar to those of non-generic classes, except that the type parameter declaration section is added after the class name.

Like generic methods, the type parameter declaration section of a generic class contains one or more type parameters, separated by commas. A generic parameter, also known as a type variable, is an identifier used to specify the name of a generic type. Because they accept one or more parameters, these classes are called paramethystized classes or paramethystized types.

Instance

The following example shows 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("Hello World"));
 
     System.out.printf("Integer Value :%d\n\n", integerBox.get());
     System.out.printf("String Value :%s\n", stringBox.get());
  }
}

Compile the above code and the results will look like this:

Integer Value :10
 
String Value :Hello World