Ring
Ring

Reputation: 2309

How does Java's Vector add a primitive array?

I'm using Java 1.3, which means that it does not have autoboxing of primitives. This means that the following code:

Vector v = new Vector();
byte b = (byte) 4;

v.addElement(b);

Does not compile, with the compiler error:

The method addElement(Object) in the type Vector is not applicable for the arguments (byte)

All primitives must be wrapped, like so:

v.addElement(new Byte(b));

With that being said, I noticed that this code compiles and runs just fine:

Vector v = new Vector();
byte[] b = new byte[]{1, 2};

v.addElement(b);

How is that possible? My version of java doesn't even have collections, and this documentation says that the method is not overloaded, it only takes Objects.

Is it the case that all arrays, even arrays of primitives, actually extend Object?

Upvotes: 1

Views: 1021

Answers (4)

pb2q
pb2q

Reputation: 59607

Al arrays, including arrays of primitive types, are Objects:

int intArray[] = new int[5];

if (intArray instanceof Object)
    System.out.println("array is Object");
else System.out.println("array not Object");

Output:

array is Object

Upvotes: 2

cheeken
cheeken

Reputation: 34655

Yes. Arrays are Objects.

From §4.3.1 of the Java Language Specification:

An object is a class instance or an array.

Upvotes: 2

Eugene
Eugene

Reputation: 120848

Is it the case that all arrays, even arrays of primitives, actually extend Object

Yes.

Upvotes: 1

John Calsbeek
John Calsbeek

Reputation: 36497

As you guessed, all arrays, even ones that contain only primitives, are Objects. They are reference types, and it simplifies Java to make every reference type an Object.

In a sense, arrays behave identically no matter what type they contain. Being "primitive" is a property of the type, not a property of the container.

Upvotes: 9

Related Questions