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.

dimo414
  • 42,340
  • 17
  • 131
  • 218
Yan
  • 143
  • 1
  • 12
  • `result.add(list)` will basically get you the same result as `result.add(new ArrayList(list))`....who said that you need to do `result.add(new ArrayList(list))`? The only reason you'd want to go with `result.add(new ArrayList(list))` is if you want to use a copy of the list for some reason. Please explain what you're trying to solve here. – musical_coder Nov 08 '15 at 19:57
  • @musical_coder please see the updated question, thanks – Yan Nov 08 '15 at 22:31

1 Answers1

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.

Community
  • 1
  • 1
dimo414
  • 42,340
  • 17
  • 131
  • 218