1

I have faced problem temporary list is also modified while original list content is being changed. Expected result should be 'Employ Original'.

public static void main(String[] args) {

        List<Employ> e = new ArrayList<Employ>();
        e.add(new Employ("Employ Original"));
        //
        List<Employ> exList = new ArrayList<>(e);
        e.get(0).name = "Employ Modified";

        // Result should be 'Employ Original' 
        System.out.println("" + exList.get(0).name);
    }

    public static class Employ {
        public String name;

        public Employ(String str) {
            this.name = str;
        }
    }
Sai's Stack
  • 1,345
  • 2
  • 16
  • 29
  • Your collections point to the same objects. Check this SO thread about [copying objects](http://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java) – mhenryk Jul 14 '15 at 15:29

2 Answers2

1

You need to clone the original objects if you want copies. The ArrayList is only making new pointers for new lists. The pointers still only point to the original objects.

Marc Johnston
  • 1,276
  • 1
  • 7
  • 16
0

This would one way of getting a copy of original array.

ArrayList<String> source = new ArrayList<String>();
source.add("test1");
source.add("test2");
ArrayList<String> copyOfSource = new ArrayList<String>();
copyOfSource.addAll(source);

second way is use

Collections.copy(destination, source);

if you dont want your collection to be modified then use

ArrayList<String> source = new ArrayList<String>();
source.add("test1");
source.add("test2");
List<String> immutablelist = Collections.unmodifiableList(source);

Here is the example how it works with custom object

Create a Employee class with two fields, firstName, lastName. Add the getter and setter methods and a constructor.

Employee emp = new Employee("Abhijit","Bashetti");
Employee emp1 = new Employee("Abhijit1","Bashetti1");
Employee emp2 = new Employee("Abhijit2","Bashetti2");

List<Employee> source = new ArrayList<Employee>();
source.add(emp);
source.add(emp1);
source.add(emp2);


ArrayList<Employee> copyOfSource = new ArrayList<Employee>();
copyOfSource.addAll(source);

for (Employee employee : source) {
   System.out.println( "source firstName ::" + employee.getFirstName() + "  source lastName :: " + employee.getLastName());
}

for (Employee employee : copyOfSource) {
   System.out.println( "firstName ::" + employee.getFirstName() + "  lastName :: " + employee.getLastName());
 }

 List<Employee> immutablelist = Collections.unmodifiableList(source);
    for (Employee employee : immutablelist) {
            System.out.println( "firstName ::" + employee.getFirstName() + "  lastName :: " + employee.getLastName());
    }
Abhijit Bashetti
  • 8,518
  • 7
  • 35
  • 47