簡體   English   中英

將三個數組列表中的元素添加到Java中的另一個列表的有效方法?

[英]efficient way to add the elements from three array lists to another list in java?

假設我有三個arrayList list1,list2和list3。 這是我的工作:

list1.addAll(list2).addAll(list3);

但是我遇到了“布爾值無法取消引用”錯誤。 不知道為什么嗎? 非常感謝。

看看方法文檔

public boolean addAll(Collection<? extends E> c)

這意味着addAll()返回一個布爾值。

當您同時合並兩個addAll()調用時,會收到該錯誤。

通過單獨執行addAll()可以輕松避免這種情況。

list1.addAll(list2);
list1.addAll(list3);

addAll()方法返回一個布爾值,該布爾值指示目標集合是否由於調用而改變。 您將第二個addAll()發送到第一個addAll()的結果,這是一個布爾值。 你要:

list1.addAll(list2);
list1.addAll(list3);

下面的做法也可以作為示例。

/*
  Copy Elements of One Java ArrayList to Another Java ArrayList Example
  This java example shows how to copy all elements of one Java ArrayList object to
  another Java ArrayList object using copy method of Collections class.
*/

import java.util.ArrayList;
import java.util.Collections;

public class CopyElementsOfArrayListToArrayListExample {

  public static void main(String[] args) {

    //create first ArrayList object
    ArrayList arrayList1 = new ArrayList();

    //Add elements to ArrayList
    arrayList1.add("1");
    arrayList1.add("2");
    arrayList1.add("3");

    //create another ArrayList object
    ArrayList arrayList2 = new ArrayList();

    //Add elements to Arraylist
    arrayList2.add("One");
    arrayList2.add("Two");
    arrayList2.add("Three");
    arrayList2.add("Four");
    arrayList2.add("Five");

    /*
      To copy elements of one Java ArrayList to another use,
      static void copy(List dstList, List sourceList) method of Collections class.

      This method copies all elements of source list to destination list. After copy
      index of the elements in both source and destination lists would be identical.

      The destination list must be long enough to hold all copied elements. If it is
      longer than that, the rest of the destination list's elments would remain
      unaffected.      
    */

    System.out.println("Before copy, Second ArrayList Contains : " + arrayList2);

    //copy all elements of ArrayList to another ArrayList using copy
    //method of Collections class
    Collections.copy(arrayList2,arrayList1);

    /*
      Please note that, If destination ArrayList object is not long
      enough to hold all elements of source ArrayList,
      it throws IndexOutOfBoundsException.
    */

    System.out.println("After copy, Second ArrayList Contains : " + arrayList2);  
  }
}

/*
Output would be
Before copy, Second ArrayList Contains : [One, Two, Three, Four, Five]
After copy, Second ArrayList Contains : [1, 2, 3, Four, Five]
*/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM