Reputation: 1338
I have the following class:
public class Profile{
String name, age, location;
}
Say that I then have the following code:
ArrayList<Profile> profiles = somePopulatedArrayList;
Profile profile = profiles.get(1);
profile.name = "New name here";
My question is when I have the above, is the .name
of the object in the ArrayList getting updated, or am I creating a completely new object here and only changing the .name
of that object while the Profile
object stored in the ArrayList still has the old name?
I'm trying to edit properties of objects in the ArrayList and I'm wondering if the above approach is correct or not?
Upvotes: 1
Views: 1167
Reputation: 6695
No New Object is Created, you are modifying the existing value.
In fact this is not a good practice,you should allow access to your class variables directly, make them as private and provide setter/getter methods for the same.
public class Profile {
private String name, age, location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
Upvotes: 2
Reputation: 77177
In Java, all variables that are object types hold references to objects. When you call get
on a collection, it returns a reference to the object that's inside it, so if you then proceed to modify that object, the changes will be seen by anyone else looking at the same object.
Upvotes: 2
Reputation: 195029
No new object was created. You've updated the object in the list, that is, the object in the list will have "New name here" as name.
In fact this you could test and see with a debugger.
Upvotes: 4