有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java提高了合并两个ArrayList的性能

我正在用下面的代码合并两个ArrayList。代码正在运行,并给了我想要的结果,但我想要一个更高效的版本。以下是条件

  1. 方法接受两个列表,两个列表中的元素按降序排列(5,4,3,2)
  2. 方法接受一个整数来决定结果ArrayList的大小
  3. 第一个输入列表的大小永远不会大于结果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) 个答案

  1. # 1 楼答案

    看起来您试图保存firstsecond的内容。如果您没有,那么这将对您很好,并将使您的代码更快、更可读:

    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调用,因为您似乎需要按相反的顺序对数据进行排序