要修改List中對(duì)象的值,可以通過索引來獲取對(duì)象,然后修改對(duì)象的屬性值。以下是一個(gè)示例代碼:
假設(shè)有一個(gè)Student類,具有屬性name和age,現(xiàn)在有一個(gè)List
import java.util.ArrayList;
import java.util.List;
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student("Alice", 20));
list.add(new Student("Bob", 22));
list.add(new Student("Charlie", 21));
// 修改第二個(gè)Student對(duì)象的屬性值
Student student = list.get(1);
student.setAge(23);
// 輸出修改后的List
for (Student s : list) {
System.out.println(s);
}
}
}
在上面的示例中,我們通過list.get(1)獲取第二個(gè)Student對(duì)象,并通過setAge方法修改了該對(duì)象的age屬性值。然后遍歷List并輸出修改后的結(jié)果。