加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么我不能在我的ArrayList上调用Collections.sort()

发布时间:2020-12-15 00:27:03 所属栏目:Java 来源:网络整理
导读:对于任何可能有这样问题的人,你可能需要“Collections.sort”,而不是“Collection.sort”,这是我在下面犯的错误. 我定义了一个定义为的类 public class Store implements Serializable,ComparableStore { ... } 我在另一个类中有一个字段定义为: ArrayListS
对于任何可能有这样问题的人,你可能需要“Collections.sort”,而不是“Collection.sort”,这是我在下面犯的错误.

我定义了一个定义为的类

public class Store implements Serializable,Comparable<Store> { ... }

我在另一个类中有一个字段定义为:

ArrayList<Store> fStores = new ArrayList<Store>();

我想对这个集合进行排序,所以在我调用的方法中:

Collection.sort(fStores);

但是,我收到以下编译错误:

The method sort(ArrayList<Store>) is undefined for the type Collection

ArrayList实现List,并从文档中:

public static <T extends Comparable<? super T>> void sort(List<T> list)

那么,为什么我会收到错误?我也尝试创建自己的Comparator后代,并将其传递给sort方法,但没有运气.

我猜这里有一些关于“< T extends Comparable<?super T>>”的内容.我不理解… ?

解决方法

您需要查看基本上有两件事情:

Collections

从Collections

This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections,“wrappers”,which return a new collection backed by a specified collection,and a few other odds and ends

所以基本上如果你必须排序或做任何这样的算法使用这个.

接下来是: – >

Collection

这是一个提供Java集合框架基础的接口.它不包括地图和排序地图.它表示一组称为其元素的对象,并具有具体实现的实现.当您想使用ArrayLists和Maps时,需要考虑这一点.

所以,在底线,你有一个静态算法来运行,它存在于集合中.所以,使用Collections.sort

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读