0

I have programmed an Algorithm that will change the passed list list.get(i).getValue().setValue("somvALUE"); to do its work.

But changing the list with setter also changes the original list. However, I still need the old List.

Is there a way to change the value only in the passed list?

EDIT: I solved my problem with a copy constructur

vovit
  • 1
  • 2

2 Answers2

1

Create a copy of the original list into a new list:

(note: in the below examples the List holds String objects)

List<String> newList = new ArrayList<>(originalList);

You can then do the changes on newList. This way your original list will stay the same, while the newList will have the changed value.

Java 8:

List<String> newList = originalList.stream()
                        .collect(Collectors.toList());
Oozeerally
  • 842
  • 12
  • 24
  • The copy consturctor of Arraylist will only create a shallow copy. And since it looks like Asker is having a list with his own custom objects (And not a List of Strings) a shallow copy wouldn't help him much – OH GOD SPIDERS Apr 27 '20 at 11:36
  • you mean .addAll in a new List? When i do that the newList also get changed – vovit Apr 27 '20 at 11:38
  • @OHGODSPIDERS yes, that is what i a have – vovit Apr 27 '20 at 11:40
  • OHGODSPIDERS you are correct. @vovit please see this answer I have found with a solution https://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents where you will need to iterate over all the items in a list and clone them one by one into the new list – Oozeerally Apr 27 '20 at 11:43
0


import java.util.ArrayList;
import java.util.List;


class CloneExample {

    public static void main(String[] args) throws CloneNotSupportedException {
        List<JavaBean> list = new ArrayList<>();
        int i = 1;
        JavaBean localBean =  ((JavaBean) list.get(i).clone()); // Clone the object
        localBean.setValue("somvALUE"); // Change that object and the input list is not tampered
    }
}

class JavaBean implements Cloneable {
    private String value;

    public void setValue(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    protected Object clone() {
        JavaBean clone;
        try {
            clone = (JavaBean) super.clone();

            //Copy new date object to cloned method
            clone.setValue(this.getValue());
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
        return clone;
    }
}

QuickSilver
  • 3,915
  • 2
  • 13
  • 29