「Java入門」java.util.ArrayList.addAll()のサンプルコード

Javaコード

import java.util.ArrayList;

public class AddlistAllDemo {

public static void main(String[] args) {
// create an empty array list1 with an initial capacity
ArrayList<Integer> cftlist = new ArrayList<Integer>(5);

// use add() method to add elements in the list
cftlist.add(20);
cftlist.add(30);
cftlist.add(55);

// let us print all the elements available in list1
System.out.println(” list1の要素下記:”);
for (Integer numVal : cftlist) {
System.out.println(“Value = ” + numVal);
}

// create an empty array list2 with an initial capacity
ArrayList<Integer> cftlist2 = new ArrayList<Integer>(5);

// use add() method to add elements in list2
cftlist2.add(15);
cftlist2.add(20);
cftlist2.add(21);
cftlist2.add(75);

// let us print all the elements available in list2
System.out.println(“list2の要素下記:”);
for (Integer numVal : cftlist2) {
System.out.println(“Value = ” + numVal);
}

// inserting all elements, list2 will get printed after list1
cftlist.addAll(cftlist2);

System.out.println(“すべての要素下記:”);
// let us print all the elements available in list1
for (Integer numVal : cftlist) {
System.out.println(“Value = ” + numVal);
}
}

}

結果

list1の要素下記:
Value = 20
Value = 30
Value = 55
list2の要素下記:
Value = 15
Value = 20
Value = 21
Value = 75
すべての要素下記:
Value = 20
Value = 30
Value = 55
Value = 15
Value = 20
Value = 21
Value = 75