有人知道如何使用泛型编写下面的代码片段并避免编译器警告吗? (@SuppressWarnings("unchecked") 被认为作弊)。
也许,通过泛型检查“左”的类型是否与“右”的类型相同?
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);
}
}
关于java - Java 泛型的乐趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1438028/