How to modify objects in an ArrayList using Java?
To modify an object in an ArrayList, first you need to retrieve the object, then make the modifications, and finally put the modified object back into the ArrayList. Here is an example code snippet:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// 创建一个ArrayList对象
ArrayList<Student> studentList = new ArrayList<>();
// 添加Student对象到ArrayList中
studentList.add(new Student("Alice", 18));
studentList.add(new Student("Bob", 20));
studentList.add(new Student("Charlie", 22));
// 修改ArrayList中的对象
// 首先找到要修改的对象
for (Student student : studentList) {
if (student.getName().equals("Bob")) {
// 修改对象的属性
student.setAge(21);
break; // 找到对象后跳出循环
}
}
// 打印修改后的ArrayList
for (Student student : studentList) {
System.out.println(student.getName() + " - " + student.getAge());
}
}
}
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
First, an ArrayList object studentList is created in the above example code, which contains three Student objects. Then, the object to be modified is found by iterating through the ArrayList, and its attributes are modified using the setAge method. Finally, the modified object information is printed by iterating through the ArrayList again.