假设我有两个ArrayLists:
name: [Four, Three, One, Two]
num: [4, 3, 1, 2]
如果我这样做:Arrays.sort(num),那么我有:
name: [Four, Three, One, Two]
num: [1, 2, 3, 4]
有没有什么方法可以对num进行排序并将其反映在名称中,这样我最终可能会:
name: [One, Two, Three, Four]
num: [1, 2, 3, 4]
?请帮帮我.我想到了比较器和对象,但根本不知道它们.
解决方法:
您应该以某种方式将名称和num字段关联到一个类中,然后具有该特定类的实例列表.在此类中,提供compareTo()方法,该方法检查数值.如果对实例进行排序,那么名称字段也将按您所希望的顺序排列.
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;
}
}
测试代码可能是这样的:
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 => One 2 => Two 3 => Three 4 => Four