Reputation: 18647
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
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
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
Reputation: 311023
No, the number of items in the array is fixed when you create it.
Upvotes: 6