Cannot pass char[] to generic method
slow down
I wrote a utility class to solve the problem. It takes a generic array and returns all combinations (no duplicates).nCr
import java.util.ArrayList;
public class fooClass {
public static void main(String[] args) {
class Utils {
public int factorial(int n) {
int p = 1;
int i = 1;
while(i <= n) {
p *= i++;
}
return p;
}
public <T> ArrayList<T[]> combinations(T[] array, int r) {
int n = array.length;
int[] vec = new int[r];
int i, j, k, m, o;
for (i = 0; i < vec.length; i++) {
//int j = vec[i];
vec[i] = i;
}
ArrayList<T[]> result = new ArrayList<T[]>();
int total = factorial(n) / (factorial(r) * factorial(n - r));
for (i = 0; i < total; i++) {
T[] combination = (T[])new Object[r];
for (k = 0; k < r; k++) {
combination[k] = array[vec[k]];
}
result.add(combination);
j = r - 1;
if (vec[j] + 1 < n) {
vec[j]++;
} else {
o = j;
while (j-- >= 0) {
if (vec[j] + 1 < n - r - (j + 1)) {
vec[j]++;
m = j + 1;
while (m++ <= o) {
vec[m] = vec[m-1] + 1;
}
break;
} //if end
} //while end
} //if-else end
}
return result;
}
};
Utils utils = new Utils();
String test = "abcde";
ArrayList<char[]> combinations = utils.combinations(test.toCharArray(), 3);
}
}
Now the problem is here, I call it "phone". When I pass, the compiler complains char[]
.
Method groups(T[], int) of type Utils does not work with parameters (char[], int)
What is the correct way to solve this problem?
anonymous
I think it's because char is a primitive type and T means object. If you use Character[]
instead char[]
, it should work fine.
char[] chars = test.toCharArray();
Character[] arg = new Character[chars.length];
for (int i = 0; i < chars.length; i++)
arg[i] = chars[i];
ArrayList<Character[]> combinations = utils.combinations(arg, 3);
This will copy all characters from the char array to the Character array and then pass it to the method.