问题描述
说我有两个的ArrayList
Say I have two ArrayLists:
name: [Four, Three, One, Two]
num: [4, 3, 1, 2]
如果我做的:Arrays.sort(NUM),那么我有:
If I do: Arrays.sort(num), then I have:
name: [Four, Three, One, Two]
num: [1, 2, 3, 4]
有什么办法我能做上的num排序,并把它体现在名称为好,这样我可能会结束:
Is there any way I can possibly do a sort on num and have it reflected in name as well, so that I might end up with:
name: [One, Two, Three, Four]
num: [1, 2, 3, 4]
?请你帮助我。我想比较器和对象,但几乎不知道他们。
? Please do help me out. I thought of Comparators and Objects, but barely know them at all.
推荐答案
您应该以某种方式的关联 名称
和 NUM
字段为一类,然后有一个特定的类的实例的列表。在这个类中,提供了一个的compareTo()
方法,它会检查的数值。如果您的实例进行排序,然后名称字段将成为你的愿望,以及顺序。
You should somehow associate name
and num
fields into one class and then have a list of instances of that specific class. In this class, provide a compareTo()
method which checks on the numerical values. If you sort the instances, then the name fields will be in the order you desire as well.
class Entity implements Comparable<Entity> {
String name;
int num;
Entity(String name, int num) {
this.name = name;
this.num = num;
}
@Override
public int compareTo(Entity o) {
if (this.num > o.num)
return 1;
else if (this.num < o.num)
return -1;
return 0;
}
}
测试code可能是这样的:
Test code could be like this:
public static void main(String[] args) {
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("One", 1));
entities.add(new Entity("Two", 2));
entities.add(new Entity("Three", 3));
entities.add(new Entity("Four", 4));
Collections.sort(entities);
for (Entity entity : entities)
System.out.print(entity.num + " => " + entity.name + " ");
}
输出:
1 =>扰2 =>两个3 =>三4 =>四
这篇关于排序2的ArrayList同时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!