1

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?

3
  • It's not a good practice to access class fields that way. You should declare them as private fields and use getters/setters instead. Commented Aug 26, 2013 at 15:46
  • 1
    profiles.get(1).setName('newName'); Commented Aug 26, 2013 at 15:47
  • 1
    There's no 'object' in the ArrayList, that's what you need to learn from this question. The list contains references (an address) that points to some object in memory. Commented Aug 26, 2013 at 15:48

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;
    }

}

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.