Java,如何使用 compareTo 对 Arraylist 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24975167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java, how to use compareTo to sort an Arraylist
提问by user3712130
Im trying to figure out how to sort an ArrayList using comparable, my code looks like this:
我试图弄清楚如何使用可比较对 ArrayList 进行排序,我的代码如下所示:
public class playerComparsion{
public static void main(String[] args){
ArrayList<Object> list = new ArrayList<Object>();
Player p1 = new Players(1,92,Zlatan);
Player p2 = new Players(2,92,Hazard);
Player p3 = new Players(1,82,Klose);
list.add(p1);
list.add(p2);
list.add(p3);
}
}
class Players implements Comparable{
int position;
String name;
int rating;
public Players(int i, int j, String string) {
this.position=i;
this.rating=j;
this.name=string;
}
public void getRating() {
System.out.println(this.rating);
}
public void getPos() {
System.out.println(this.position);
}
public void getName() {
System.out.println(this.name);
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
}
I want to sort the Arraylist based on the attribute rating. I suppose I should use the compareTo function but I have no idea how, can someone help me?
我想根据属性评级对 Arraylist 进行排序。我想我应该使用 compareTo 函数,但我不知道如何使用,有人可以帮助我吗?
回答by Makoto
Don't use a raw type with Comparable
. Instead, use Comparable<Players>
. This way, you have direct access to the object you care about without having to cast from Object
.
不要将原始类型与Comparable
. 相反,使用Comparable<Players>
. 这样,您就可以直接访问您关心的对象,而无需从Object
.
The sample compareTo
would be this:
样本compareTo
是这样的:
public int compareTo(Player other) {
return rating - other.getRating();
}
Then, you would actually have to...sort it, using Collections.sort()
.
然后,您实际上必须...对其进行排序,使用Collections.sort()
.
Collections.sort(list);
The reason for Comparable<Players>
is that Comparable
itself is defined as taking a generic type T
.
原因Comparable<Players>
是它Comparable
本身被定义为采用泛型类型T
。
回答by janos
Instead of making Player
implement Comparable
, you get more flexibility by implementing Comparator<Player>
classes. For example:
而不是使的Player
实现Comparable
,你会得到通过实现更大的灵活性Comparator<Player>
类。例如:
class PlayerComparatorByRating implements Comparator<Player> {
@Override
public int compare(Player o1, Player o2) {
return o1.getRating() - o2.getRating();
}
}
class PlayerComparatorByName implements Comparator<Player> {
@Override
public int compare(Player o1, Player o2) {
return o1.getName().compareTo(o2.getName());
}
}
After all, Player
has multiple fields, it's easy to imagine that sometimes you might want to order players differently. A great advantage of this approach is the single responsibility principle: a Player
class does only one thing, encapsulates player data. Instead of adding one more responsibility (sorting), it's better to move that logic in another class.
毕竟,Player
有多个字段,很容易想象有时您可能想要对玩家进行不同的排序。这种方法的一大优点是单一职责原则:一个Player
类只做一件事,封装玩家数据。与其添加更多职责(排序),不如将该逻辑移到另一个类中。
You could use these comparators with Collections.sort
, for example:
您可以将这些比较器与 一起使用Collections.sort
,例如:
Collections.sort(list, new PlayerComparatorByRating());
System.out.println(list);
Collections.sort(list, new PlayerComparatorByName());
System.out.println(list);
Extra tips
额外提示
Your class seems to be named Players
. It's better to rename to Player
.
你的班级似乎被命名为Players
。最好重命名为Player
.
The getName
, getRating
, getPos
methods should not return void
and print the result, but return the field values instead.
的getName
,getRating
,getPos
方法不应返回void
打印出结果,但返回的字段值来代替。
Use better names for the constructor arguments, for example:
为构造函数参数使用更好的名称,例如:
Player(int position, int rating, String name) {
this.position = position;
this.rating = rating;
this.name = name;
}
Use the right type of list to store players:
使用正确类型的列表来存储玩家:
List<Player> list = new ArrayList<Player>();
Please format your code properly. Any IDE can do that.
请正确格式化您的代码。任何 IDE 都可以做到这一点。
Suggested implementation
建议实施
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Player {
private int position;
private int rating;
private final String name;
Player(int position, int rating, String name) {
this.position = position;
this.rating = rating;
this.name = name;
}
public int getRating() {
return rating;
}
public int getPos() {
return position;
}
public String getName() {
return name;
}
@Override
public String toString() {
return String.format("%s:%d:%d", name, position, rating);
}
}
class PlayerComparatorByRating implements Comparator<Player> {
@Override
public int compare(Player o1, Player o2) {
return o1.getRating() - o2.getRating();
}
}
class PlayerComparatorByName implements Comparator<Player> {
@Override
public int compare(Player o1, Player o2) {
return o1.getName().compareTo(o2.getName());
}
}
public class PlayerComparatorDemo {
public static void main(String[] args){
List<Player> list = new ArrayList<Player>();
Player p1 = new Player(1, 92, "Zlatan");
Player p2 = new Player(2, 92, "Hazard");
Player p3 = new Player(1, 82, "Klose");
list.add(p1);
list.add(p2);
list.add(p3);
Collections.sort(list, new PlayerComparatorByRating());
System.out.println(list);
Collections.sort(list, new PlayerComparatorByName());
System.out.println(list);
}
}
回答by FruitDealer
Try this.
尝试这个。
public class Comparator_Test {
public static void main(String[] args) {
ArrayList<Players> list = new ArrayList<Players>();
Players p1 = new Players(1,92,"Zlatan");
Players p2 = new Players(2,92,"Hazard");
Players p3 = new Players(1,82,"Klose");
list.add(p1);
list.add(p2);
list.add(p3);
PlayerComparator comparator = new PlayerComparator();
System.out.println(list);
Collections.sort(list, comparator);
System.out.println(list);
}
}
class Players {
int position;
String name;
int rating;
public Players(int i, int j, String string) {
this.position=i;
this.rating=j;
this.name=string;
}
public void getRating() {
System.out.println(this.rating);
}
public void getPos() {
System.out.println(this.position);
}
public void getName() {
System.out.println(this.name);
}
public String toString() {
return rating + "";
}
}
class PlayerComparator implements Comparator<Players> {
@Override
public int compare(Players o1, Players o2) {
if(o1.rating > o2.rating) {
return 1;
}
if(o1.rating < o2.rating) {
return -1;
}
return 0;
}
}