1

有人知道如何使用泛型编写下面的代码并避免编译器警告吗?(@SuppressWarnings("unchecked") 被认为是作弊)。

而且,也许,通过泛型检查 "left" 的类型是否与 "right" 的类型相同?

public void assertLessOrEqual(Comparable left, Comparable right) {
    if (left == null || right == null || (left.compareTo(right) > 0)) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
    }
}
4

3 回答 3

12

这也适用于 Comparable 类型的子类:

public <T extends Comparable<? super T>> void assertLessOrEqual(T left, T right) {
  if (left == null || right == null || left.compareTo(right) > 0) {
    String msg = "["+left+"] is not less than ["+right+"]";
    throw new RuntimeException("assertLessOrEqual: " + msg);
  }
}
于 2009-09-17T11:00:55.193 回答
3

这个怎么样:

public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
  if (left == null || right == null || (left.compareTo(right) > 0)) {
    String msg = "["+left+"] is not less than ["+right+"]";
    throw new RuntimeException("assertLessOrEqual: " + msg);
  }
}

它可能会变得更通用一点,但也只能让它变得更复杂:)

于 2009-09-17T10:48:00.210 回答
2

您不能通过泛型检查运行时“左”的类型是否与“右”的类型相同。Java 泛型是通过类型擦除实现的,因此有关泛型类型参数的信息在运行时会丢失。

public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
    if (left == null || right == null || (left.compareTo(right) > 0)) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
    }
}
于 2009-09-17T10:46:24.580 回答