### 在两个ArrayLists（Java）中排序和交换元素

``````subList1
subList2
``````

``````subList1: [amulet, map, stone, sword]
subList2: [bottle, shield, wand]
``````

``````subList1: [amulet, bottle, map, shield]
subList2: [stone, sword, wand]
``````

``````Collections.sort(subList1);
Collections.sort(subList2);

//[amulet, map, stone, sword]
//[bottle, shield, wand]

for (int i1 = 0; i1 < subList1.size(); i1++) {

for (int i2 = 0; i2 < subList2.size(); i2++) {

if (subList1.get(i1).compareTo(subList2.get(i1)) < 0) {

// first run: element 0: subList1 = amulet, subList2 = bottle

String temp = subList1.get(i1);
subList1.set(i1, subList2.get(i1));
subList2.set(i1, subList1.get(i1));
``````

``````if (subList1.get(i1).compareTo(subList2.get(i1)) < 0)
``````

#### 4 个答案:

``````if (subList1.get(i1).compareTo(subList2.get(i1)) < 0)
``````

``````if (subList1.get(i1).compareTo(subList2.get(i2)) < 0) // you wrote i1 instead of i2
_____
``````

• 合并这两个列表以创建`newList = subList1 + subList2`
• `newList`
• 进行排序
• `subList2`的末尾获取等于`newList`长度的子列表。
• `subList1`
• 的开头获取等于`newList`长度的子列表

``````Collection<String> subList1 = Arrays.asList("amulet", "map", "stone", "sword");
Collection<String> subList2 = Arrays.asList("bottle", "shield", "wand");

// Merge two collection in a single list
List<String> mergedList = new ArrayList<>(subList1);

Collections.sort(mergedList);

// Assign subList from mergedList back to original Collection reference
subList1 = mergedList.subList(0, subList1.size());
subList2 = mergedList.subList(subList1.size(), mergedList.size());

System.out.println(subList1);  // [amulet, bottle, map, shield]
System.out.println(subList2);  // [stone, sword, wand]
``````

``````int length = subList1.length();
Collections.sort(subList1); // sort

// split them both up again
subList2 = subList1.subList(length, subList1.length());
subList1 = subList1.subList(0, length);
``````

``````List<String> merged = new ArrayList<String>();
``````

``````Collections.sort(merged);
``````

``````int k = subList1.size();
``````

``````subList1.clear();
``````subList2.clear();