Issue in modifying the objects of original list?

后端 未结 2 907
一个人的身影
一个人的身影 2021-01-25 03:47

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

public static v         


        
相关标签:
2条回答
  • 2021-01-25 04:12

    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.

    0 讨论(0)
  • 2021-01-25 04:12

    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());
        }
    
    0 讨论(0)
提交回复
热议问题