数组是对象,所有对象都来自一个类。如果我执行以下代码:
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
。我的问题是:
instanceof
运算符,应该如何使用?如果我执行System.out.println(arr instanceof Object);
,它会完美地工作。 最佳答案
This is all specified in the JLS。数组是动态创建的Object
,它们实现了Serializable
和Cloneable
。
您看到这种情况的原因是由于对象是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
与原始语言一起使用会导致编译时错误)。关于java - Java中的数组的类是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31055448/