有人知道如何使用泛型编写下面的代码并避免编译器警告吗? (@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);
}
}
答案 0 :(得分: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);
}
}
答案 1 :(得分: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);
}
}
可能会使 little 位变得更加通用,但只会让它变得更复杂:)
答案 2 :(得分:2)
您无法通过泛型检查“left”的类型是否与运行时“right”的类型相同。 Java泛型是通过type erasure实现的,因此有关泛型类型参数的信息在运行时会丢失。
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);
}
}