Latest web development tutorials

Java Generics

Java generics (generics) is a new feature introduced in JDK 5, generics provide compile-time type safety testing mechanism that allows the programmer to compile-time type of the detected illegal.

The generic nature of the parameterized type, data type means that the operation is specified as a parameter.

Suppose we have such a requirement: write a sorting method, capable of shaping the array, an array of strings or any other type of array to sort, how to achieve?

The answer is that you can use Java generics.

Use Java Generics, we can write a generic method to sort an array of objects. Then, call the generic method to an array of integers, floating point arrays, strings, arrays, and sorted.


Generic method

You can write a generic method that can be received when calling different types of parameters. To the parameter type generic method, the compiler deal with each method call from the transfer appropriately.

Here are the rules to define a generic method:

  • All declare a generic method has a type parameter declaration section (separated by angle brackets), the type parameter declaration section before the method return type (in the following example <E>).
  • Each type parameter declaration section contains one or more type parameters, separated by commas between parameters. A generic parameter, also known as a type variable identifier is used to specify the name of a generic type.
  • Type parameters can be used to declare the return type, and can be obtained as a generic actual parameter type placeholder.
  • Declare a generic method and other methods, like body. Note that type parameter type can only represent a reference type, not a primitive type (like int, double, char, etc.).

Examples

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

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 results are as follows:

整型数组元素为:
1 2 3 4 5 

双精度型数组元素为:
1.1 2.2 3.3 4.4 

字符型数组元素为:
H E L L O 

There bounded type parameters:

There may be times you will want to restrict who is allowed to pass to a kind type parameter of type range. For example, a digital method of operation may only want to accept instances of Number or Number subclasses. This is the purpose of bounded type parameter.

To declare a bounded type parameter, the type parameter name is listed first, followed by the keyword extends, finally followed its upper bound.

Examples

The following example demonstrates the "extends" How to Use in a generic sense meaning "extends" (category) or "implements" (Interface). The example of a generic method returns the maximum 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:

3, 4 和 5 中最大的数为 5

6.6, 8.8 和 7.7 中最大的数为 8.8

pear, apple 和 orange 中最大的数为 pear

Generic class

Similar declarations and statements of non-generic class of generic class, in addition to the class name, append the parameter type declaration section.

And generic methods, generic class type parameter declaration section also contains one or more type parameters, separated by commas between parameters. A generic parameter, also known as a type variable identifier is used to specify the name of a generic type. 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 results are as follows:

整型值为 :10

字符串为 :本教程