Reputation: 53
I am trying to solve a problem of getting all the sets of a Subset S=[1,2,3]. And I am using the recursion to solve this. I am trying to make a empty ArrayList containing a emptyList in the base Case. And while making my own ans I am getting above mentioned as compile time error.
I am already tried the eclipse suggestion addAll but still I am getting the error.
public static ArrayList<ArrayList<Integer>> relatedSubSets(ArrayList<Integer> A, int index){
if(index == A.size()){
ArrayList<ArrayList<Integer>> br=new ArrayList<ArrayList<Integer>();
ArrayList<Integer> emptyList=new ArrayList<Integer>();
br.add(emptyList); //Making an arraylist containing empty list
return br;``
}
ArrayList<ArrayList<Integer>> rr=relatedSubSets(A,index+1); // Getting the recursion result in it.
ArrayList<ArrayList<Integer>> mr=new ArrayList<>();
for(int i=0;i<rr.size();i++){
ArrayList<Integer> ans=rr.get(i);
mr.add(ans);
mr.add(ans.add(0,A.get(index))); //Error in this line of the code
}
System.out.println(mr);
return mr;
}
Expected Output is all Subsets. Getting compile time error but.
Upvotes: 0
Views: 474
Reputation: 327
mr.add(ans.add(0,A.get(index)));
//Error in this line of the code
Your are trying to add void return value to arraylist. List add method return void. So you are getting following error,
The method add(ArrayList) in the type ArrayList> is not applicable for the arguments (void)
Try below,
ans.add(0,A.get(index)); //Add Integer to ArrayList
mr.add(ans); //Add ArrayList<Integer> to ArrayList
Upvotes: 0
Reputation: 42511
Compiler does a pretty good job in detecting errors:
You've missed extra ">" symbol:
// wrong:
ArrayList<ArrayList<Integer>> br=new ArrayList<ArrayList<Integer>();
// ok:
ArrayList<ArrayList<Integer>> br=new ArrayList<ArrayList<Integer>>();
Now, this still doesn't compile because of this line:
mr.add(ans.add(0,A.get(index)));
Note that and.add(...)
returns a boolean
so probably you wanted something like this:
ans.add(0, A.get(index));
mr.add(ans);
In this case think however that the reference is mutable so that if you change the ans
array later, then mr
's element will also change... so you need just two aforementioned lines in the loop:
for(int i=0;i<rr.size();i++){
ArrayList<Integer> ans=rr.get(i);
mr.add(ans);
ans.add(0,A.get(index));
}
Now this compiles, so the "technical" part is resolved, and you can concentrate on solving the "logical" part of the task, Good luck :)
Upvotes: 1