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:
- 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 toLast name
after adding toArrayList
? - Does every Collection behave this way?