Generics: Why Class <Integer []> clazzIntArray = int []. Class does not work

The following lines:

Class<Integer> clazzInteger = Integer.class; Class<Integer> clazzInt = int.class; 

Valid and will compile / execute even if:

 if(clazzInt.equals(clazzInteger)) { System.out.println("clazzInt equals clazzInteger"); }else { System.out.println("clazzInt and clazzInteger are not equal"); } 

clazzInt and clazzInteger are not equal will be printed. But Class<int> clazzInt = int.class; not working of course.

So why can't this analogy apply to array types?

 Class<int[]> clazzIntArray = int[].class; Class<Integer[]> clazzIntArray = int[].class; // type mismatch: //cannot convert from Class<int[]> to Class<Integer[]> 

But

 Class<int[]> clazzIntArray = int[].class; // this is ok 

Now I am puzzled why Class<Integer[]> clazzIntArray = int[].class not valid? What does Class<int[]> mean? And why does the analogy between types of arrays and non-arrays not work?

+4
source share
3 answers

Autoboxing has nothing to do with this. The Java language specification indicates (in JLS 15.8.2 ) which type of T.class has:

  • If T is a reference type, T.class is of type Class<T>
  • If T is a primitive type, T.class is of type Class<wrapper class of T>

What is it. int.class is of type Class<Integer> because the specification says so. int[].class is of type Class<int[]> because the specification says so. Class<int[]> and Class<Integer[]> are not compatible types in Java.

+1
source

Under the hood, Autoboxing / Unboxing occurs on individual elements within the array. not with all array type.

Java cannot magically convert an entire primitive array into a Wrapper array. Here is a separate element and an array consisting of individual elements.

For example: An array of baskets and fruits inside the baskets are elements (int / Integer's)

+1
source

Auto-update only works with single "instances" - int can be automatically added to Integer , and Integer can be sent to int . However, this does not apply to arrays. For example, the instruction int[] arr = new Integer[10]; will not compile. The same is true for manipulating these classes through reflection.

0
source

All Articles