Reputation: 75
I am trying to generate all possible permutations of a given list in a generic function. I think I have the function code correct. However, during testing time I keep getting compiler errors from my main program. Please help!
import java.util.*;
class perms <E>{
public List<List<E>> generatePerm(List<E> original) {
if (original.size() == 0) {
List<List<E>> result = new ArrayList<List<E>>();
result.add(new ArrayList<E>());
return result;
}
E firstElement = original.remove(0);
List<List<E>> returnValue = new ArrayList<List<E>>();
List<List<E>> permutations = generatePerm(original);
for (List<E> smallerPermutated : permutations) {
for (int index=0; index <= smallerPermutated.size(); index++) {
List<E> temp = new ArrayList<E>(smallerPermutated);
temp.add(index, firstElement);
returnValue.add(temp);
}
}
return returnValue;
}
public static void main(String[] params){
List<Integer> p = new ArrayList<Integer> ();
p.add(1);
p.add(2);
System.out.print(p.toString());
List<List<Integer>> resultantList=generatePerm(p);
System.out.print(resultantList.toString());
}
}
I keep generating the following error in my testing portion:
perms.java:33: generatePerm(java.util.List<E>) in perms<E> cannot be applied to (java.util.List<java.lang.Integer>)
List<List<Integer>> resultantList=generatePerm(p);
Upvotes: 0
Views: 1337
Reputation: 15418
generatePerm
function is not static
: as main
is static
you won't call a non-static
function from a static
context.<E>
after the access modifier of generatePerm
declaration to specify that this function is generic.So working version of generatePerm
function would be:
public static <E>List<List<E>> generatePerm(List<E> original) {
//your code block
}
Upvotes: 1
Reputation: 1269
You forgot 2 things:
generatePerm()
static
generatePerm()
generic adding <E>
Perms
Result:
public class Perms
...
public static <E> List<List<E>> generatePerm(List<E> original)
...
Btw you don't have to declare <E>
in class definition because here you use it only in static context.
Upvotes: 0
Reputation: 111259
The error message is not helpful at all; the real problem is that you are calling a method that belongs to an object, but don't provide an object. If it wasn't for generics you would get the famous "cannot call non-static method from static context" error.
One way to fix it is creating an object:
perms<Integer> computation = new perms<Integer>();
List<List<Integer>> resultantList = computation.generatePerm(p);
Upvotes: 1