What is an array class in Java

Arrays are objects, and all objects are from a class. If I executed the following code:

public class Test { public static void main(String[] args) { String str = "Hello"; System.out.println(str.getClass()); } } 

The output of class java.lang.String .

But if I do the following:

 public class Test { public static void main(String[] args) { int arr[] = new int[10]; System.out.println(arr.getClass()); } } 

Output signal class [I

My questions:

  • What is an array class?
  • Why is this the result?
  • If I would like to use the instanceof operator, how to use it? If I execute System.out.println(arr instanceof Object); It works great.
+6
source share
2 answers

All of this is specified in JLS . Arrays are dynamically created by Object , which implement Serializable and Cloneable .

The reason you come across is because the object is represented in Class#getName .

Since you can use instanceof with reifiable Object types , and the array is very verifiable (that is, concrete, not general), you can use instanceof with arrays:

 System.out.println(arr instanceof int[]); // true System.out.println(arr instanceof String[]); // false 

The problem with your arr instance Object is that the <X> instanceof Object not useful, since everything is an Object (except for primitives, but using instanceof with primitives is a compile-time error).

+4
source

Adding to another answer, the type can actually be decoded using the string you received as JVMS: Chapter 4. The class File Format :

 B byte signed byte C char Unicode character code point in the Basic Multilingual Plane, encoded with UTF-16 D double double-precision floating-point value F float single-precision floating-point value I int integer J long long integer L ClassName ; reference an instance of class ClassName S short signed short Z boolean true or false [ reference one array dimension 

You got class [I So [ , which is the size of the array and I , which is an integer. An array of integers describes the type.

+1
source

Source: https://habr.com/ru/post/989755/


All Articles