有人知道如何使用泛型编写下面的代码并避免编译器警告吗? (@SuppressWarnings(“未选中”)被视为作弊)。

并且,也许,通过泛型检查“左”的类型。与“正确”的类型相同?

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);
    }
}
有帮助吗?

解决方案

这也适用于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);
  }
}

其他提示

这个怎么样:

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);
  }
}

它可能会变得更加通用 little ,但只会使它变得更复杂:)

您无法通过泛型检查“left”的类型是否与运行时“right”的类型相同。 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);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top