【问题标题】:What is the class of the Arrays in JavaJava中数组的类是什么
【发布时间】:2015-09-12 08:39:53
【问题描述】:

数组是对象,所有对象都来自一个类。如果我执行以下代码:

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

输出是class java.lang.String

但如果我执行以下操作:

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

输出为class [I

我的问题是:

  1. 数组的类别是什么?
  2. 为什么会这样?
  3. 如果我想使用instanceof 运算符,我应该如何使用它?如果我执行System.out.println(arr instanceof Object);,它会完美运行。

【问题讨论】:

标签: java arrays


【解决方案1】:

除了另一个答案之外,该类型实际上可以使用您在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

你得到的是class [I。所以[ 是一个数组维度,I 是一个整数。整数数组描述了类型。

【讨论】:

    【解决方案2】:

    This is all specified in the JLS。数组是动态创建的Objects,它实现了SerializableCloneable

    您看到的原因是因为对象是represented in Class#getName

    因为您可以使用instanceof with reifiable Object types,并且数组是非常可具体化的(即具体的,而不是通用的),您可以将instanceof 与数组一起使用:

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

    arr instance Object 的问题在于 <X> instanceof Object 没有用,因为 一切 都是 Object(除了原语,但使用带有原语的 instanceof 是编译时错误)。

    【讨论】:

    • 感谢@TJCrowder,这是一个非常好的例子。
    猜你喜欢
    • 2017-06-13
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 2016-12-29
    • 1970-01-01
    • 2010-12-19
    相关资源
    最近更新 更多