有谁知道如何使用泛型编写下面的代码并避免编译器警告?(@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);
}
}
Run Code Online (Sandbox Code Playgroud)
new*_*cct 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
902 次 |
| 最近记录: |