1

I Created an array like this:

    Class<? extends AbstractItem>[] itemList = {
            ItemNew.class,
            ItemLoad.class,
            ItemSave.class,
            ItemSetting.class,
            ItemEnd.class
    };

but java tells me:

Cannot create a generic array of Class<? extends AbstractItem>  

If I don't specify the Class generics java warns me with:

Class is a raw type. References to generic type Class<T> should be parameterized    

So who is right? and even more why doesn't it allow me to limit the Class types?

edit: the mentioned duplicate is not solving my problem, cause if I do not specify the type of the array, I can create it with compiler warning. So it is indeed possible but I am looking for the right way to achieve this)

dlmeetei
  • 7,297
  • 3
  • 25
  • 34
Ranndom
  • 139
  • 11

1 Answers1

0

The java don't allow create generic array except all type arguments are unbounded wildcards.

Consider the following code:

    List<String>[] strings=new List<String>[1];    //1
    List<Integer> integers=Arrays.asList(1);
    Object[] objects=strings;
    objects[0]=integers;
    String s=strings[0].get(0);
    System.out.println(s);      //2

See the statement 1,if java allow create the generic type array,the above code will get a exception java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String on statement 2 whitout any warnings at run-time.This is not correctly ,so the java mustn't create generic type array.

If you change List<String>[] stringList=new List<String>[1]; //1 to List<String>[] stringList=new List[1];,the code will can compile correctly,but the compiler will get a warning like Unchecked assignment,of course,your can use @SuppressWarnings("unchecked") to suppress the warning.

In the JLS 10.6 Array Initializers section,there is a rule:

It is a compile-time error if the component type of the array being initialized is not reifiable

and the JLS 4.7 Reifiable Types define what is reifiable types,the first one is :

It refers to a non-generic class or interface type declaration.
dabaicai
  • 941
  • 6
  • 9
  • The situation you're describing also arises (at compile time) without any generics (e.g. try it with String[], Object[] and assign a Boolean, it compiles). It's caused by assigning a Whatever[] array to a variable declared Object[], without even getting a compiler warning. In the non-generics situation, at least you get an ArrayStoreException at runtime. – Ralf Kleberhoff Aug 06 '17 at 10:49