[英]Best way to remove one arraylist elements from another arraylist
[英]Most efficient way (according RAM/CPU consumption) to add elements from one ArrayList to another ArrayList to specific position
我有兩個ArrayList A和B。 我需要結合這兩個ArrayLists。 將所有元素從ArrayList_ B放置到ArrayList_ A的特定位置。
ArrayList_ A中的元素組成應類似於:a1b1a2b2a3b3 ....
但是,盡我所能,以最有效的方式做到這一點。
規則 :不要更改創建ArrayList_ B中 。
如您所見,在我的示例中,最有效的方法是Method2。 但是對於巨大的ArrayList來說仍然很慢。
請提出最有效的方法。 感謝您的關注:)。
公共類解決方案{
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);
}
}
彼得的答案可能是最好的。 但是,如果您經常這樣做,則可以定義自己的類。 骨架代碼(可能是越野車) 假設您的兩個輸入數組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()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.