Skip to content Skip to sidebar Skip to footer

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[] arg

Solution 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.

Solution 2:

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

ArrayList<String> source = newArrayList<String>();
source.add("test1");
source.add("test2");
ArrayList<String> copyOfSource = newArrayList<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 = newArrayList<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());
    }

Post a Comment for "Issue In Modifying The Objects Of Original List?"