0

I have the following code for the problem "Given a set of distinct integers, return all possible subsets. If nums = [1,2,3], a solution is [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]."

public class Solution {
public ArrayList<ArrayList<Integer>> subsets(int[] num) {
    ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    if(num == null || num.length == 0) {
        return result;
    }
    ArrayList<Integer> list = new ArrayList<Integer>();
    Arrays.sort(num);  
    subsetsHelper(result, list, num, 0);

    return result;
}


private void subsetsHelper(ArrayList<ArrayList<Integer>> result,
ArrayList<Integer> list, int[] num, int pos) {

    result.add(new ArrayList<Integer>(list));

    for (int i = pos; i < num.length; i++) {
        list.add(num[i]);
        subsetsHelper(result, list, num, i + 1);
        list.remove(list.size() - 1);
    }
}

In result.add(new ArrayList<Integer>(list)) why do I need to use new ArrayList<Integer>(list))? I know simply using result.add(list) would make the items in the result all the same, but I want to know the reason.

2
  • result.add(list) will basically get you the same result as result.add(new ArrayList<Integer>(list))....who said that you need to do result.add(new ArrayList<Integer>(list))? The only reason you'd want to go with result.add(new ArrayList<Integer>(list)) is if you want to use a copy of the list for some reason. Please explain what you're trying to solve here. Commented Nov 8, 2015 at 19:57
  • @musical_coder please see the updated question, thanks Commented Nov 8, 2015 at 22:31

1 Answer 1

2
new ArrayList<Integer>(list)

This is called a copy constructor, "It is used to create a copy of an existing object of the same class."

Without the copy constructor each call to result.add(list) would add a reference to the same list repeatedly to result. With the copy constructor a new list is created with the current values of list. That way subsetHelper() can repeatedly modify list without also changing the lists already stored in result.

Make sure you understand how Java passes around method parameters; it's not complicated, but it is critical to being an effective Java programmer.

Sign up to request clarification or add additional context in comments.

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.