How to add multiple objects to a list in Java?
To add multiple objects to a list in Java, you can use the add() method along with a loop. Here is an example code:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// 创建一个包含多个对象的数组
String[] objectsToAdd = {"object1", "object2", "object3"};
// 使用循环将数组中的对象逐个添加到列表中
for (String obj : objectsToAdd) {
list.add(obj);
}
// 打印列表中的内容
System.out.println(list);
}
}
In this example, we start by creating a list of string type called ‘list’, and define an array named ‘objectsToAdd’ that contains multiple objects. Then, we use a for loop to add each object from the array to the list one by one, and finally print the contents of the list. You can modify the type and quantity of objects as needed.