Java Object[] 数组可以容纳什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32915711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What can an Object[] array hold?
提问by Dorian Dore
I am new to the Java Programming language and had a question about arrays. String[]
arrays hold strings. Array[]
arrays hold other arrays. What about an Object[]
array? Clearly, these would hold Object
s. But, since Object
is the superclass for everything in Java, does this mean an Object[]
array can hold every type of Object
in Java? In other words, can an array hold objects that are child classes of the object the array was created to hold? Can a Number[]
array hold an integer?
我是 Java 编程语言的新手,有一个关于数组的问题。String[]
数组保存字符串。Array[]
数组保存其他数组。怎么样的Object[]
阵列?显然,这些将成立Object
。但是,既然Object
是 Java 中所有东西的超类,这是否意味着Object[]
数组可以容纳Object
Java 中的所有类型?换句话说,数组是否可以保存作为创建该数组要保存的对象的子类的对象?一个可以Number[]
阵列持有的整数?
采纳答案by David Yee
Yes but you can learn a lot by trying it for yourself with a small program:
是的,但是您可以通过一个小程序亲自尝试来学习很多东西:
public class Example {
public static void main(String[] args) {
String string = "String";
Integer integer = new Integer(1);
int integerPrimitive = 2;
Float floatBoxed = new Float(1.23);
float floatPrimitive = 1.23f;
// Can hold different types inheriting from Object
Object[] objects = new Object[] {
string,
integer,
integerPrimitive,
floatBoxed,
floatPrimitive };
// Can hold anything that inherits from Number; cannot hold a String
Number[] numbers = new Number[] {
integer,
integerPrimitive,
floatBoxed,
floatPrimitive };
for (int i = 0; i < objects.length; i++) {
System.out.println("objects[" + i + "] = " + objects[i]);
}
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
}
}
Output:
输出:
objects[0] = String
objects[1] = 1
objects[2] = 2
objects[3] = 1.23
objects[4] = 1.23
numbers[0] = 1
numbers[1] = 2
numbers[2] = 1.23
numbers[3] = 1.23
The key to knowing what an array container can hold is first observing if the object types are the same or if the object is a sub-class of the array container type.
了解数组容器可以容纳什么的关键是首先观察对象类型是否相同,或者对象是否是数组容器类型的子类。
In your question if a Number
can hold an Integer
, you should see the inheritance of Integer
in the Javadocs that it inherits from Number
. You can also see that Number
inherits from Object
.
在您的问题中,如果 aNumber
可以容纳Integer
,您应该Integer
在它继承自的 Javadoc 中看到 的继承Number
。您还可以看到Number
继承自Object
.