java提高了合并两个ArrayList的性能
我正在用下面的代码合并两个ArrayList
。代码正在运行,并给了我想要的结果,但我想要一个更高效的版本。以下是条件
- 方法接受两个列表,两个列表中的元素按降序排列(5,4,3,2)
- 方法接受一个整数来决定结果
ArrayList
的大小李> - 第一个输入列表的大小永远不会大于结果
ArrayList
的大小李>
代码:
public ArrayList<Integer> mergeList(ArrayList<Integer> first,ArrayList<Integer> second, int n){
//case 1: when both list are null.
if(first == null && second == null )
return null;
//case 2: when first list is null but second list have elements
else if( first == null && second != null){
return second.size() >=n ? new ArrayList<Integer>(second.subList(0, n)) : second;
}
//case 3: when first list have record and second list is null
else if(first != null && second == null){
return first;
}
//case 4: when both list have elements
else {
first.addAll(second);
Collections.sort(first);
Collections.reverse(first);
return first.size()>=n ? new ArrayList<Integer>(first.subList(0, n)) : first;
}
}
}
# 1 楼答案
看起来您试图保存
first
和second
的内容。如果您没有,那么这将对您很好,并将使您的代码更快、更可读:这之所以更快,是因为对于每个
addAll()
,Java必须迭代所有项,将它们复制到tempList
。我保留了Collections.reverse
调用,因为您似乎需要按相反的顺序对数据进行排序