1

Say below is my bean class:

public class Employee {

    private String name = null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

This is my main class:

import java.util.ArrayList;

public class MainClass {

    public static void main(String[] args) {

        Employee employee = new Employee();
        employee.setName("First name");

        ArrayList<Employee> empList = new ArrayList<Employee>();
        empList.add(employee);

        employee.setName("Last name");

        for (Employee emp : empList) {
            System.out.println(emp.getName());
        }
    }
}

When I executed the output is: Last name

My question is:

  1. As I know Java is pass-by-value or rather pass-by-copy-of-the-variable-value then does the copy of employee object was saved in the ArrayList or it references the original object of Employee as the object value is getting changed to Last name after adding to ArrayList?
  2. Does every Collection behave this way?
Community
  • 1
  • 1
Vishrant
  • 15,456
  • 11
  • 71
  • 120
  • 2
    when a primitive is passed to a function it is passed-by-value, when an object is passed to a function the reference to said object is passed-by-value. – Jonny Henly Mar 02 '15 at 10:49

3 Answers3

4

A copy of the employee reference was saved in the ArrayList, but since it refers to the same Employee instance, changing the instance later via the employee reference affects the element stored in the ArrayList.

Yes, every Collection behaves this way, since the Collections don't create copies of the instances passed to them, they just store references to those instances.

Eran
  • 387,369
  • 54
  • 702
  • 768
2
  1. As I know Java is pass-by-value or rather pass-by-copy-of-the-variable-value then does the copy of employee object was saved in the ArrayList or it references the original object of Employee as the object value is getting changed to Last name after adding to ArrayList?

The reference will be passed-by-value. So, there will be 2 references pointing to the same Employee instance. One reference is employee and another is in the arraylist.

  1. Does every Collection behave this way?

Yes. Actually, this is NOT a property of collections. This is the way java was designed. All mutable reference types behave in this way.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

The local variable employee and the first element of the list are two different references to the same object. That's why modifying the referenced object (via setName, for example) on one of them will be visible via the other.

However, if you replace the reference by assigning a different one, it will not effect the other.

E.g.:

employee = new Employee();
employee.setName("Vishrant");

Now employee and the first element of the list reference different objects, so the element in the array will not be called "Vishrant".

Mureinik
  • 297,002
  • 52
  • 306
  • 350