Java ArrayList addAll()方法
java.util.ArrayList.addAll(int index, Collection<? extends E> c) 方法追加所有指定集合中的元素到此列表的指定索引位置上。
1 语法
public boolean addAll(int index, Collection<? extends E> c)
2 参数
index:需要插入的索引位置。
c:这是包含要添加到此列表的元素的集合。
3 返回值
如果此列表由于调用而更改,则此方法返回true。
4 示例
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* java.util.ArrayList.addAll(int index, Collection<? extends E> c)方法的例子
*/
import java.util.ArrayList;
public class Demo {
public static void main(String args[]) {
// create an empty array list1 with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(12);
arrlist.add(20);
arrlist.add(45);
// let us print all the elements available in list1
System.out.println("Printing list1:");
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
// create an empty array list2 with an initial capacity
ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5);
// use add() method to add elements in list2
arrlist2.add(25);
arrlist2.add(30);
arrlist2.add(31);
arrlist2.add(35);
// let us print all the elements available in list2
System.out.println("Printing list2:");
for (Integer number : arrlist2) {
System.out.println("Number = " + number);
}
// inserting all elements of list2 at third position
arrlist.addAll(2, arrlist2);
System.out.println("Printing all the elements");
// let us print all the elements available in list1
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
输出结果为:
Printing list1:
Number = 12
Number = 20
Number = 45
Printing list2:
Number = 25
Number = 30
Number = 31
Number = 35
Printing all the elements
Number = 12
Number = 20
Number = 25
Number = 30
Number = 31
Number = 35
Number = 45
热门文章
优秀文章