1

Please be patience with me if this question is too easy for you. I am new to Java generics, and encounter a coding example that I'm confused of. It wants to return all possible subsets when a set of distinct integers is given.

My questions:

  1. Why does the code below use List<List<Integer>>? Can you use List<Integer> instead?

  2. What's the technical term for a structure like List<List<Integer>>? I'd like to read more online.

Thank you so much for your help!

public class Example { public List<List<Integer>> subsets(int[] nums) { } } 
2
  • 1
    List<List<Integer>> is a list of lists. Think of it as a matrix. A List<Integer> would simply be a line. Commented Jan 11, 2016 at 5:31
  • It's the list equivalent of a 2 dimensional array. Commented Jan 11, 2016 at 5:35

4 Answers 4

3

One collection (List) will return only one subset, to return all subsets you need collection of collections. For example if initial set is (1,2,3) all subsets would be (1,2,3), (1,2), (1,3), (2,3), (1), (2), (3). As you see each of them are list. To return this kind of result you should use List of List.

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

Comments

2

The key part is all possible subsets, which means multiple values per entry (or a List of List(s)). You could not represent

1,2,3 4,5,6 

as two distinct sets without a collection of collections (or an array of arrays).

Comments

1

Can you use List instead? Yes and no.

You can always find a projection from a finitie n-dimensional structure to a 1 dimensional structure. Eg. simply go through all the lists and add the members to 1 single list.

But you can't (always/most of the time) reverse the process, once you have a List<Integer> it's sometimes impossible to go back to a List<List<Integer>>, or it is really complicated and not worth the computing time.

Comments

1

Its too simple. List<List<Integer>> is nothing but a List of List of integers. Consider it as 2D array. consider a,b,c as List<Integer>

 a-> 1,2,3,4,5.. b->5,6,8.. c->4,6,9,7,4.. 

then List<List<Integer>> xyz is nothing but the list of a,b,c.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.