我正在使用以下代码合并两个ArrayList
。代码正在运行并给我想要的结果,但我想要一个更高效的版本。这是条件。
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;
}
}
}
答案 0 :(得分:1)
这取决于你的意思是“更高效”。
就什么而言?内存,CPU,可读性?
根据您的上述代码,我做出以下假设:
private List<Integer> mergeList(List<Integer> list1, List<Integer> list2, final int newSize) {
// Enforce null object pattern
if (list1 == null) {
list1 = Collections.emptyList();
}
if (list2 == null) {
list2 = Collections.emptyList();
}
// If duplicates are not desirable, a TreeSet would perform automatic sorting.
List<Integer> result = new ArrayList<Integer>(list1);
result.addAll(list2);
Comparator<Integer> reverseSortComparator = new Comparator<Integer>() {
@Override
public int compare(final Integer o1, final Integer o2) {
return o2.compareTo(o1);
}
};
Collections.sort(result, reverseSortComparator);
if (result.size() > newSize) {
return result.subList(0, newSize);
} else {
return result;
}
}
答案 1 :(得分:0)
您似乎正在尝试保留first
和second
的内容。如果你不是,那么这对你来说会很好,并且会使你的代码更快更可读:
public ArrayList<Integer> mergeList(ArrayList<Integer> first,ArrayList<Integer> second, int maxLength){
//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;
}
//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 if(first != null && second != null){
first.addAll(second);
Collections.sort(first); //want to merge these two line into one
Collections.reverse(first);
}
return (ArrayList) first.size() > maxLength ? first.subList(0, n) : first;
}
这更快的原因是因为每个addAll()
,Java必须遍历所有项目,将它们复制到tempList
。我保留了Collections.reverse
调用,因为您似乎需要按相反的顺序排列数据。