Java Sort with Comparable [英] Java Sort with Comparable

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

问题描述

我有一个 Person 对象的 ArrayList.Personnameageheight.我的目标是对这个 ArrayList 进行排序.我已经实现了 Comparable 并定义了 compareTo() 但是当我尝试对其进行排序时,它给了我这个错误:

I have an ArrayList of Person objects. A Person has name, age and height. My goal is to sort this ArrayList<Person>. I have implemented Comparable<Person> and have defined compareTo() but when I try to sort it, it give me this error:

ArrayList 类型中的 sort(Comparator) 方法不适用于参数 ()"

The method sort(Comparator) in the type ArrayList is not applicable for the argument ()"

我的理解是,如果你实现了 Comparable,然后定义了 compareTo,其他一切都会为你神奇地完成.

The way I understand is that if you implement Comparable and then define compareTo everything else is magically done for you.

有人可以解释一下这是如何工作的以及为什么我会收到此错误吗?

Can some one explain how to this works and why I am getting this error?

推荐答案

当您在其中添加新元素时,您可以使用使用 Comparable 接口对其元素进行排序的结构:

Either you use a structure which uses the Comparable interface to order its elements when you add a new element inside it :

TreeSet<Person> persons = new TreeSet<>();
Person personOne = ...
Person personTwo = ...
persons.add(personOne);
persons.add(personTwo);

要么使用 ListCollections.sort(List<T> list) 方法,该方法将要排序的列表作为参数(有一个重载这种方法,但它与您的情况无关):

Either you use a List and the Collections.sort(List<T> list) method which takes as argument the list you want to sort (there is an overload of this method but it is not relevant in your case):

List<Person> persons = new ArrayList<>();
Person personOne = ...
Person personTwo = ...
persons.add(personOne);
persons.add(personTwo);
Collections.sort(persons);

使用 TreeSet,元素在添加后立即排序,而使用 List,元素在添加时不会排序.
只有,调用 Collections.sort() 方法对列表进行排序.

With the TreeSet, the elements are sorted as soon as added and with the List, the elements are not sorted when you add them.
Only, the call to the Collections.sort() method sorts the list.

这篇关于Java Sort with Comparable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆