例:
Object[] x = new Object[2];
x[0] = 3; // integer
x[1] = "4"; // String
System.out.println(x[0].getClass().getSimpleName()); // prints "Integer"
System.out.println(x[1].getClass().getSimpleName()); // prints "String"
Run Code Online (Sandbox Code Playgroud)
这让我想知道:第一个对象元素是类的实例Integer?或者它是原始数据类型int?有区别,对吧?
所以,如果我想确定第一个元素的类型(是整数,双精度,字符串等),该怎么做?我用x[0].getClass().isInstance()吗?(如果是,怎么样?),还是我用别的东西?
不是你问的,但如果有人想确定数组中允许的对象的类型:
Oject[] x = ...; // could be Object[], int[], Integer[], String[], Anything[]
Class classT = x.getClass().getComponentType();
Run Code Online (Sandbox Code Playgroud)
有之间的差异int,并Integer只有一个Integer可以进入的Object [],但自动装箱/拆箱使得它难以确定下来.
一旦将值放入数组中,它就会被转换为Integer并且它的起源被遗忘.同样地,如果你声明int []并放入Integer它,它会被转换成int现场,并且没有Integer保留它的痕迹.
x是一个对象数组 - 因此它不能包含基元,只能包含对象,因此第一个元素的类型为Integer.正如@biziclop所说,它通过自动装箱成为一个整数
要检查变量的类型,请使用instanceof:
if (x[0] instanceof Integer)
System.out.println(x[0] + " is of type Integer")
Run Code Online (Sandbox Code Playgroud)