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 Objects. 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?
1 Answer
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.