通用方法和有界类型参数

原文: https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html

有界类型参数是通用算法实现的关键。考虑以下方法,计算数组T []中大于指定元素elem的元素数。

  1. public static <T> int countGreaterThan(T[] anArray, T elem) {
  2. int count = 0;
  3. for (T e : anArray)
  4. if (e > elem) // compiler error
  5. ++count;
  6. return count;
  7. }

该方法的实现很简单,但它不能编译,因为大于运算符(> )仅适用于原始类型,如shortint漂浮字节char 。你不能使用>运算符来比较对象。要解决此问题,请使用由Comparable&lt; T&gt;界定的类型参数。接口:

  1. public interface Comparable<T> {
  2. public int compareTo(T o);
  3. }

生成的代码将是:

  1. public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
  2. int count = 0;
  3. for (T e : anArray)
  4. if (e.compareTo(elem) > 0)
  5. ++count;
  6. return count;
  7. }