Java泛型问题,在编译时,提示警告: 需要: List<T>

错误提示:

++++++++++

警告: [unchecked] 方法调用未经过检查: 将类 Collections中的方法 s

ort应用到给定的类型


Collections.sort(books);

                ^

需要: List<T>

找到: List<BookDetails>

其中, T是类型变量:


T扩展已在方法 <T>sort(List<T>)中声明的Comparable<? super T>

1 个警告

++++++++++


下面是源代码:


  public Collection<BookDetails> getBooks()throws Exception{

    Connection con=null;

    PreparedStatement prepStmt=null;

    ResultSet rs =null;

    List<BookDetails> books = new ArrayList<BookDetails>();

    try {

      con=getConnection();

      String selectStatement = "select * " + "from BOOKS";

      prepStmt = con.prepareStatement(selectStatement);

      rs = prepStmt.executeQuery();


      while (rs.next()) {


        BookDetails bd = new BookDetails(rs.getString(1), rs.getString(2), rs.getString(3),

           rs.getFloat(4), rs.getInt(5), rs.getString(6),rs.getInt(7));

        books.add(bd);

      }

    }finally{

      closeResultSet(rs);

      closePrepStmt(prepStmt);

      closeConnection(con);

    }

    

    Collections.sort(books);           // 出现警告的地方

    return books;

  }

问题: 这是什么原因?T不是只是一个类型符号吗?为什么必须要找到List<T>?


杨魅力
浏览 1483回答 2
2回答

人到中年有点甜

&nbsp;public static <T extends Comparable<? super T>> void sort(List<T> list) {&nbsp; &nbsp; &nbsp; &nbsp; Object[] a = list.toArray();&nbsp; &nbsp; &nbsp; &nbsp; Arrays.sort(a);&nbsp; &nbsp; &nbsp; &nbsp; ListIterator<T> i = list.listIterator();&nbsp; &nbsp; &nbsp; &nbsp; for (int j=0; j<a.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i.set((T)a[j]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }需要注意这里:T extends Comparable<? super T>

元芳怎么了

应该是你java版本过低。java1.5以上版本支持@SuppressWarning注解
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java