Java Generics 简明教程

Java Generics - Multiple Bounds

类型参数可以有多个界限。

A type parameter can have multiple bounds.

Syntax

public static <T extends Number & Comparable<T>> T maximum(T x, T y, T z)

其中

Where

  1. maximum − maximum is a generic method.

  2. T − The generic type parameter passed to generic method. It can take any Object.

Description

传递给泛型类 Box 的 T 是一个类型参数,并且应当是 Number 类的子类型,还必须实现 Comparable 接口。如果类作为界限传递,则应当在接口之前传递,否则会发生编译时错误。

The T is a type parameter passed to the generic class Box and should be subtype of Number class and must implments Comparable interface. In case a class is passed as bound, it should be passed first before interface otherwise compile time error will occur.

Example

使用任意你选择的编辑器创建以下 Java 程序。

Create the following java program using any editor of your choice.

package com.tutorialspoint;

public class GenericsTester {
   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("Max of %.1f,%.1f and %.1f is %.1f\n\n",
         6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));
   }

   public static <T extends Number
      & Comparable<T>> T maximum(T x, T y, T z) {
      T max = x;
      if(y.compareTo(max) > 0) {
         max = y;
      }

      if(z.compareTo(max) > 0) {
         max = z;
      }
      return max;
   }

   // Compiler throws error in case of below declaration
   /* public static <T extends Comparable<T>
      & Number> T maximum1(T x, T y, T z) {
      T max = x;
      if(y.compareTo(max) > 0) {
         max = y;
      }

      if(z.compareTo(max) > 0) {
         max = z;
      }
      return max;
   }*/
}

这会产生以下结果 −

This will produce the following result −

Output

Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8