Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create generic array? [duplicate]

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");

}

}
like image 818
Dims Avatar asked Feb 19 '23 11:02

Dims


2 Answers

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....

like image 176
Kumar Vivek Mitra Avatar answered Feb 28 '23 12:02

Kumar Vivek Mitra


(T[][]) new Object[size][size]

like image 29
Amit Deshpande Avatar answered Feb 28 '23 12:02

Amit Deshpande