同时对两个arrayLists进行排序

``````name: [Four, Three, One, Two]
num:  [4, 3, 1, 2]
``````

``````name: [Four, Three, One, Two]
num:  [1, 2, 3, 4]
``````

``````name: [One, Two, Three, Four]
num:  [1, 2, 3, 4]
``````

？请帮帮我。我想到了比较器和对象，但根本不知道它们。

4 个答案:

``````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>();
Collections.sort(entities);

for (Entity entity : entities)
System.out.print(entity.num + " => " + entity.name + " ");
}
``````

1 =＆gt;一个2 =＆gt;两个3 =＆gt;三个4 =＆gt;四

，而不是对实际数组进行排序
``````a[i] = i for i = 0..n
``````

``````bool compare( int a, int b ) { return num[a] < num[b]; }
``````

``````int[] num = {4, 3, 1, 2};
String[] name = {"Four", "Three", "One", "Two"};
TreeMap<Integer,String> sortedMap = new TreeMap<Integer,String>();
for (int i=0; i<num.length; i++) sortedMap.put(num[i], name[i]);
// Resulting sortedMap: {1=One, 2=Two, 3=Three, 4=Four}
``````

用法

``````// The key can be any type that implements Comparable, Dupes are allowed
List<Integer> key = Arrays.asList(4, 3, 1, 2, 1);

// List Types do not need to be the same
List<String> list1 = Arrays.asList("Four", "Three", "One", "Two", "One");
List<Character> list2 = Arrays.asList('d', 'c', 'a', 'b', 'a');

// Sorts key, list1, list2 using key as the sorting key.
keySort(key, key, list1, list2);
``````

``````key:   [1, 1, 2, 3, 4]
list1: [One, One, Two, Three, Four]
list2: [a, a, b, c, d]
``````