给定两个不同大小的数组列表,我需要在新的ArrayList中返回它们的排序联合。
这是代码。我不断得到一个数组越界错误,如果我不按顺序排列它们(随机)。
public static ArrayList<Integer> merge(ArrayList<Integer> l1, ArrayList<Integer> l2) {
int i = 0;
int pointer1 = 0;
int pointer2 = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
while (list.size() < ((l1.size() + l2.size()))) {
if (pointer1 < 11 && pointer2 < 21) {
if (l1.get(pointer1) == l2.get(pointer2)) {
list.add(l1.get(pointer1));
list.add(l2.get(pointer2));
pointer1++;
pointer2++;
} else if (l1.get(pointer1) > l2.get(pointer2)) {
list.add(l1.get(pointer1));
pointer1++;
} else if (l2.get(pointer2) > l1.get(pointer1)){
list.add(l2.get(pointer2));
pointer2++;
}
} else if (pointer2 < 20) {
list.add(l2.get(pointer2));
pointer2++;
} else if (pointer1 < 10) {
list.add(l2.get(pointer2));
pointer2++;
}
}
return list;
}
答案 0 :(得分:2)
Hello下面是合并和排序两个ArrayList的简单代码.Hope对你很有帮助..
public static ArrayList<Integer> merge(ArrayList<Integer> l1, ArrayList<Integer> l2) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.addAll(l1);
list.addAll(l2);
Collections.sort(list);
return list;
}