Java ArrayList add() 方法
示例
将一个列表中的项添加到另一个列表中
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
ArrayList<String> brands = new ArrayList<String>();
brands.add("Microsoft");
brands.add("W3Schools");
brands.add("Apple");
brands.addAll(cars);
System.out.println(brands);
}
}
定义和用法
addAll()
方法将一个集合中的所有项添加到列表中。
如果提供了索引,新项将被放置在指定的索引处,将列表中所有后续元素向前推。
如果未提供索引,新项将被放置在列表的末尾。
语法
以下之一
public boolean addAll(Collection<T> items)
public boolean addAll(int index, Collection<T> items)
T
指的是列表中项的数据类型。
参数值
参数 | 描述 |
---|---|
index | 可选。在列表中添加项的位置。 |
items | 必需。一个包含要添加到列表中的项的集合。 |
技术详情
返回 | 如果列表发生更改,则为 true ,否则为 false 。 |
---|---|
抛出 |
IndexOutOfBoundsException - 如果索引小于零或大于列表的大小。NullPointerException - 如果集合为 null。 |
更多示例
示例
在列表的指定位置添加项
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
ArrayList<String> brands = new ArrayList<String>();
brands.add("Microsoft");
brands.add("W3Schools");
brands.add("Apple");
brands.addAll(1, cars);
System.out.println(brands);
}
}
相关页面
❮ ArrayList 方法