Sai's Stack
Sai's Stack

Reputation: 1385

Issue in modifying the objects of original list?

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

Upvotes: 1

Views: 241

Answers (2)

Abhijit Bashetti
Abhijit Bashetti

Reputation: 8658

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

Upvotes: 0

Marc Johnston
Marc Johnston

Reputation: 1286

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.

Upvotes: 1

Related Questions