在 Java 中addAll(int, Coll C)方法的作用是什么?
java.util.ArrayList 类的方法 addAll(int index, Collection<? extends E> c) 从指定位置开始将指定集合中的所有元素插入此列表。它将当前该位置的元素(如果存在)和任何后续元素向右移动(增加它们的索引)。新元素将以指定集合的迭代器返回的顺序出现在列表中。
示例
import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { ArrayList<Integer> arrlist = new ArrayList<Integer>(5); arrlist.add(12); arrlist.add(20); arrlist.add(45); System.out.println("Printing list1:"); for (Integer number : arrlist) { System.out.println("Number = " + number); } ArrayList<Integer> arrlist2 = new ArrayList<Integer>(5); arrlist2.add(25); arrlist2.add(30); arrlist2.add(31); arrlist2.add(35); System.out.println("Printing list2:"); for (Integer number : arrlist2) { System.out.println("Number = " + number); } arrlist.addAll(2, arrlist2); System.out.println("Printing all the elements"); 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
广告