1

So when I insert an Arraylist A into an Arraylist constructor I expect a new Arraylist object B created with the same set of objects as A. In my case I have

Arraylist<Arraylist<Integer>> powerSet
Arraylist<Arraylist<Integer>> OG

Both powerSet and OG seem to share the same reference despite OG being constructed from powerSet like this:

ArrayList<ArrayList<Integer>> OG  = new ArrayList<>(powerSet);

Here is the full code:

public static ArrayList<ArrayList<Integer>> generatePower (ArrayList<Integer> s){
    ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>();
    generatePower(s,powerSet);
    return powerSet;
}
public static void generatePower(ArrayList<Integer> s,ArrayList<ArrayList<Integer>> powerSet ){
    if(s.size()==0){
        powerSet.add(s);
        return;
    }
    else{
        int temp = s.remove(0);
        generatePower(s,powerSet);
        ArrayList<ArrayList<Integer>> OG  = new ArrayList<>(powerSet);
        for(ArrayList<Integer> el: OG){
            el.add(temp); //for some reason any changes I make to OG here is
                         //reflected in the powerSet
        }
        powerSet.addAll(OG);

    }
}

Why do OG and powerSet have the same reference and how do I make OG be a new arraylist containing all of powerSet's elements without have OG share powerSet's reference

2 Answers 2

1

The ArrayList constructor doesn't clone elements; it just copies references over. Here's one way to make a deep copy using streams

List<List<Integer>> copy = powerSet.stream()
        .map(ArrayList::new)
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

0

ArrayList<ArrayList<Integer>> OG = new ArrayList<>(powerSet);

this line pass all elements (copy references) stored in powerSet to OG.

It's work in the same way like example:

List<User> usersList_1 = Arrays.asList(user1, user2, user3);
List<User> usersList_2 = new ArrayList(userList_1);

user1.setName("John");

userList_2.get(0).getName();

output: John

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.