本文介绍了有趣的Java泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道如何使用泛型编写下面的代码片段,并避免编译器警告? (@SuppressWarnings(unchecked)被认为是作弊)。



也许,通过泛型来检查left的类型与

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>


解决方案

可与Comparable类型的子类一起工作:

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


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" ?

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);
    }
}
解决方案

This works with subclasses of Comparable types too:

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泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 11:31