我是Java的新手......
我有两个ArrayLists:
subList1
subList2
它们已经被另一个方法填充,并且在运行时,列表包含以下字符串:
subList1: [amulet, map, stone, sword]
subList2: [bottle, shield, wand]
我需要做的是对两个列表进行排序,以便subList1按字母顺序位置包含小于subList2中元素的所有元素。两个列表大小也必须保持不变。
预期产出:
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));
我还得到以下行的IndexOutOfBoundsException:
if (subList1.get(i1).compareTo(subList2.get(i1)) < 0)
任何帮助非常感谢。谢谢。
答案 0 :(得分:1)
你有什么(不正确)
if (subList1.get(i1).compareTo(subList2.get(i1)) < 0)
它应该是什么(正确)
if (subList1.get(i1).compareTo(subList2.get(i2)) < 0) // you wrote i1 instead of i2
_____
答案 1 :(得分:1)
通过分别对两个列表进行排序,然后对它们进行迭代,使您的任务变得复杂。我建议你遵循这个方法:
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);
mergedList.addAll(subList2);
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]
答案 2 :(得分:0)
这将修复您的异常:
if(subList1.get(i1).compareTo(subList2.get(i2))&lt; 0)
要对两个列表进行排序,您需要获取第一个列表的大小。 (即int len = subList1.length()),将它们合并,排序,然后根据您先保存的'len'变量将其拆分为2。
这样的事情,也许是:
int length = subList1.length();
subList1.addAll(subList2); // add both lists together
Collections.sort(subList1); // sort
// split them both up again
subList2 = subList1.subList(length, subList1.length());
subList1 = subList1.subList(0, length);
这可以通过多种方式加以解决,但应该为您提供一个好的起点。长度变量是不必要的(我们知道subList 2的长度),但是易于阅读代码。
答案 3 :(得分:0)
合并两个列表:
List<String> merged = new ArrayList<String>();
merged.addAll(subList1);
merged.addAll(subList2);
对合并列表进行排序:
Collections.sort(merged);
获取subList1的大小:
int k = subList1.size();
清除并向subList1添加从0到k的合并列表的条目:
subList1.clear();
subList1.addAll(merged.subList(0, k));
清除并向subList2添加从k到n的合并列表的条目(其中n是合并列表的大小):
subList2.clear();
subList2.addAll(merged.subList(k, merged.size()));