int[] array = new int[10]; // Length is fixed when the array is created.
The length of an array is established when the array is created. After creation, its length is fixed.
Why does it have to be so?
int[] array = new int[10]; // Length is fixed when the array is created.
The length of an array is established when the array is created. After creation, its length is fixed.
Why does it have to be so?
As other answers have noted, fixed size is part of the definition, and you'd have to talk to the original authors to find the truth.
But as a general point, it is significantly more complex to implement a variable-length container, and there are a number of strategies for achieving it under the hood (linked list, memory re-allocation ...).
Had the authors defined arrays to be variable-length back in the early 1990s, there would have been several unwanted consequences:
a.length
becomes mutable;java.util.Vector
back in the day, and now Java Collections, Guava etc).To sum up, arrays in the C-language family from which Java was born are broadly expected to be simple tools for building higher-level structures - back then, there was zero surprise at the fixed size restriction. We now have a choice of implementations of such structures (LinkedList
, ArrayList
, etc) which provide a selection of runtime behaviours, and most devs use those abstractions.
That's in the definition of Java array
s:
An array is a container object that holds a fixed number of values of a single type
(see here).
Use an ArrayList
for a variable-sized array implementation.
© 2022 - 2024 — McMap. All rights reserved.