0

I have for example the following class

public class MyClass<T> {
private int id;
T content;
}

and in other part of my project I want to create a method that return Myclass<byte[]>[]

I wrote this code

Myclass<byte[]>[] tempArray=new Myclass<byte[]>[4];

> the eclipse says "cannot create a generic array of Myclass<byte[]

anyone knows how to solve it?

tit
  • 1

2 Answers2

1

You cannot create arrays of parametrized types, as stated in the Java SE tutorial

 (...)You cannot create arrays of parameterized types. 
 For example, the following code does not compile:

List<Integer>[] arrayOfLists = new List<Integer>[2];  // compile-time error

The following code illustrates what happens 
when different types are inserted into an array:

Object[] strings = new String[2];
strings[0] = "hi";   // OK
strings[1] = 100;    // An ArrayStoreException is thrown.

If you try the same thing with a generic list, there would be a problem:

Object[] stringLists = new List<String>[];  // compiler error, but pretend it's allowed
stringLists[0] = new ArrayList<String>();   // OK
stringLists[1] = new ArrayList<Integer>();  // An ArrayStoreException should be thrown,
                                            // but the runtime can't detect it.

If arrays of parameterized lists were allowed, 
the previous code would fail to throw the desired ArrayStoreException.(...)

It has nothing to do with primitive types or objects, as you can see from the example below

public class Generics<T> {
    T x;

    public static void main(String[] args) {
        Generics<byte[]> g = new Generics<byte[]>();
        g.x = new byte[10];
        g.x[1] = 1;
    }

    Generics<T>[] getMyArray(){
        Generics<Byte[]>[] array = new Generics<Byte[]>[1]; <<<<error
    }
}
Leo
  • 6,177
  • 3
  • 28
  • 48
0

In java you cannot create an array of an generic type.
this question has good answers

But basically at runtime arrays need to information on its objects type, so you must know the array's type when you create the array. But since you have no idea what T is at runtime, you cannot create the array

Community
  • 1
  • 1
AmitS
  • 150
  • 1
  • 9