最有效的方式(根据内存/CPU消耗)将元素从一个数组列表添加到另一个数组列表的特定位置



我有两个数组列表AB。我需要把这两个数组列表组合起来。将ArrayList_B到ArrayList_A中的所有元素放到指定位置

ArrayList_A中的元素组成应该是这样的:a1b1a2b2a3b3…

但我要以最有效的方式,尽我所能。

规则:不修改create ArrayList_B.

如你所见,在我的例子中最有效的方法是Method2。但是对于巨大的数组列表来说还是很慢。

请建议最有效的方法。谢谢你的关注:)。

public class Solution {

public static void main(String[] args) {
    Method1();
    Method2();
    Method3();
}
private static void Method3() {
    ArrayList<Object> a = new ArrayList<>();
    ArrayList<Object> b = new ArrayList<>();
    for (int i = 0; i < Math.pow(2, 15); i++) {
        a.add("a" + i);
    }
    for (int i = 0; i < Math.pow(2, 15); i++) {
        b.add("b" + i);
    }
    ArrayList<Object> aa = new ArrayList<>(a);
    a.ensureCapacity(2*aa.size());
    a.clear();
    long time1 = System.currentTimeMillis();

    for (int i = 0; i<b.size();i++) {
        a.add(aa.get(i));
        a.add(b.get(i));
    }
    long time2 = System.currentTimeMillis();
    System.out.println(time2 - time1);
}
private static void Method2() {
    ArrayList<Object> a = new ArrayList<>();
    ArrayList<Object> b = new ArrayList<>();
    for (int i = 0; i < Math.pow(2, 15); i++) {
        a.add("a" + i);
    }
    for (int i = 0; i < Math.pow(2, 15); i++) {
        b.add("b" + i);
    }
    long time1 = System.currentTimeMillis();
    int size = a.size();
    a.add(b.get(0));
    for (int i = 1; i < size; i++) {
        a.add(a.get(i));
        a.add(b.get(i));
    }
    a.subList(1, size).clear();
    long time2 = System.currentTimeMillis();
    System.out.println(time2 - time1);
}
private static void Method1() {
    ArrayList<Object> a = new ArrayList<>();
    ArrayList<Object> b = new ArrayList<>();
    for (int i = 0; i < Math.pow(2, 15); i++) {
        a.add("a" + i);
    }
    for (int i = 0; i < Math.pow(2, 15); i++) {
        b.add("b" + i);
    }
    long time1 = System.currentTimeMillis();
    a.add(1, b.get(0));
    for (int i = 1; i < b.size(); i++) {
        a.add((2 * i + 1), b.get(i));
    }
    long time2 = System.currentTimeMillis();
    System.out.println(time2 - time1);
}

}

Peter的答案可能是最好的。但是,如果您经常这样做,也许可以定义您自己的类。框架代码,可能有bug, 假设你的两个输入数组a和b永远不会改变,你永远不想在创建后改变组合列表,等等…:

public class DualList<E> extends AbstractList<E> {
   final List<E> a; 
   final List<E> b;
   public DualList(List<E> a, List<E> b) {
      this.a = a;  this.b = b;
   }
   public E get(int idx) {
      int half = idx >> 1;
      if ((idx & 1) == 1)
         return this.b.get(half);
      else
         return this.a.get(half);
   }
   // not sure what else you need or want to override...
}

这显然会更快地"创建"组合列表,因为它几乎什么都不做,但是每次调用get()来检索元素时,这将会慢一点。所以最后的决定取决于你调用get()的次数

最新更新