要修改List中對象的值,可以通過索引來獲取對象,然后修改對象的屬性值。以下是一個示例代碼:
假設有一個Student類,具有屬性name和age,現在有一個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));
// 修改第二個Student對象的屬性值
Student student = list.get(1);
student.setAge(23);
// 輸出修改后的List
for (Student s : list) {
System.out.println(s);
}
}
}
在上面的示例中,我們通過list.get(1)獲取第二個Student對象,并通過setAge方法修改了該對象的age屬性值。然后遍歷List并輸出修改后的結果。