Possible Duplicate:
Java how to: Generic Array creation
How to create an array of type T[]
in Java? I can't use Arrays.newInstance()
since I have no objects of Class<T>
. Is there a generic version of newInstance
somewhere?
My method prototype follows:
public <T> T[][] distribute(T ... balls) {
T[][] answer = ????
// filling answer with data
return answer;
}
UPDATE
Sorry in example above I can take class from balls
. But suppose I have no such a variable.
public <T> T[][] distribute() {
T[][] answer = ????
// filling answer with data
return answer;
}
or
class<T> {
public T[][] distribute() {
T[][] answer = ????
// filling answer with data
return answer;
}
}
UPDATE2
This example also does not work:
public abstract class GenericArray<T> {
abstract public T create();
public T[] gen1() {
T[] ans = (T[]) new Object[3];
ans[0] = create();
ans[1] = create();
ans[2] = create();
return ans;
}
public Integer[] gen2() {
Integer[] ans = new Integer[3];
ans[0] = new Integer(0);
ans[1] = new Integer(0);
ans[2] = new Integer(0);
return ans;
}
public static void main(String[] args) {
GenericArray<Integer> a = new GenericArray<Integer>() {
@Override
public Integer create() {
return new Integer(0);
}
};
Integer[] b = a.gen2();
Integer[] c = a.gen1(); // this causes ClassCastException
System.out.println("done");
}
}
1. Arrays
are Not Generic
2. Thats the reason Arrays
are checked during compile as well as runtime, where as Collections
can be Generic and its checked only during the compile time....
(T[][]) new Object[size][size]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With