问题描述
任何人都知道如何使用泛型编写下面的代码片段,并避免编译器警告? (@SuppressWarnings(unchecked)被认为是作弊)。也许,通过泛型来检查left的类型与 可与Comparable类型的子类一起工作: Anybody knows how to write the piece of code below using generics AND avoiding compiler warnings ? (@SuppressWarnings("unchecked") is considered cheating). And, maybe, checking via generics that the type of "left" is the same as the type of "right" ? This works with subclasses of Comparable types too: 这篇关于有趣的Java泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
pre $ public void assertLessOrEqual(Comparable left,Comparable right){
if(left == null || right == null ||(left.compareTo(right)> 0)){
String msg =[+ left +]不小于[+ right +];
抛出新的RuntimeException(assertLessOrEqual:+ msg);
$ / code>
public< T extends Comparable< super T>> void assertLessOrEqual(T left,T right){
if(left == null || right == null || left.compareTo(right)> 0){
String msg =[+左+]不小于[+右+];
抛出新的RuntimeException(assertLessOrEqual:+ msg);
}
}
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);
}
}
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);
}
}