To modify a member of an object stored in an ArrayList in Java, you need to follow these steps:
ArrayList.ArrayList after modification. The change will be reflected in the list automatically.Here is an example to illustrate this process:
Suppose you have a class Person:
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } // Getter and setter for name public String getName() { return name; } public void setName(String name) { this.name = name; } // Getter and setter for age public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } And you have an ArrayList of Person objects:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Person> people = new ArrayList<>(); people.add(new Person("Alice", 30)); people.add(new Person("Bob", 25)); // Suppose you want to update the age of Bob for (Person person : people) { if (person.getName().equals("Bob")) { person.setAge(26); // Update Bob's age } } // Print the updated list for (Person person : people) { System.out.println(person); } } } In this example:
ArrayList named people contains objects of the Person class.setName method of the Person object to update the name.Person objects are mutable, the changes are reflected in the ArrayList automatically.Note:
public, you can access it directly (e.g., person.age = 26). However, using getter and setter methods is considered better practice in terms of object-oriented design.String), you would need to replace the entire object in the list after making modifications. Immutable objects do not allow modifications to their fields once created.persistent sql-function react-proptypes temp-tables python-docx galleryview relational-database pgadmin-4 creation vbscript