📅  最后修改于: 2023-12-03 15:01:35.227000             🧑  作者: Mango
java.lang.Object[4]
is an array of 4 Java objects. In Java, every object is an instance of the Object
class, which is the root of the class hierarchy. Therefore, Object[4]
is an array of 4 objects of any type.
The declaration of an array of 4 objects of any type is as follows:
Object[] objectArray = new Object[4];
This creates an array of 4 null references to objects of any type.
An array of java.lang.Object
can store objects of different types, since every class in Java is a subclass of java.lang.Object
. This can be useful when you need to store objects of different types, but don't want to create type-specific arrays.
Object[] mixedObjects = new Object[4];
mixedObjects[0] = "hello"; // a String object
mixedObjects[1] = 123; // an Integer object (autoboxing)
mixedObjects[2] = new Date(); // a Date object
mixedObjects[3] = new HashMap(); // a HashMap object
When retrieving objects from an Object[]
array, you need to cast them to their original type. This can be done using the (type)
casting operator.
String stringObject = (String) mixedObjects[0];
Integer integerObject = (Integer) mixedObjects[1];
Date dateObject = (Date) mixedObjects[2];
HashMap hashMapObject = (HashMap) mixedObjects[3];
Since every object is an instance of java.lang.Object
, you can use any of the methods defined in the Object
class on the objects stored in an Object[]
array. These include methods such as toString()
, equals()
, and hashCode()
.
String stringObject = (String) mixedObjects[0];
System.out.println(stringObject.toString());
java.lang.Object[4]
is a versatile array that can hold objects of any type. It provides flexibility in situations where you need to store objects of different types in the same array. However, care needs to be taken when casting objects to prevent runtime errors.