John Hoffman
John Hoffman

Reputation: 18647

How is obtaining the size of a Java array object O(1)?

I am just beginning to learn Java and heard that getting the size of an array is O(1). Why is it not O(n)?

Mustn't the java virtual machine count the number of items in the array?

Upvotes: 1

Views: 115

Answers (3)

Matt
Matt

Reputation: 11805

As mentioned above, it's a special bytecode function:

http://en.wikipedia.org/wiki/Java_bytecode_instruction_listings

arraylength be arrayref → length get the length of an array

Upvotes: 1

Stephen C
Stephen C

Reputation: 719386

Mustn't the java virtual machine count the number of items in the array?

That is not necessary. The JVM representation for an array has a special field that gives the length of the array instance, and a special bytecode for accessing it. When it needs the length, the JVM uses these.

(It is also true that an array's length is fixed when the array has been created ... but that doesn't directly answer the question. Hypothetically, the JVM could still count elements. However, I find it hard to see how the JVM would decide where / when to stop counting elements. How would it know when the bits it is looking at don't represent a valid value of the array base-type?)

Upvotes: 3

user207421
user207421

Reputation: 311023

No, the number of items in the array is fixed when you create it.

Upvotes: 6

Related Questions