Why are Java arrays fixed length?
Asked Answered
D

2

6
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?

Dubuffet answered 7/3, 2016 at 14:41 Comment(5)
because it was designed like this. If you want to dynamically change the size, use a collection.Chaworth
It was designed like this...ok but why?Dubuffet
what is your own opinion about it ?Binturong
@HichamMoustaid: if you want the why, you'll have to ask those who made the decision.Chaworth
@HitchamMoustaid would you like to accept an answer?Emmaline
E
12

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:

  • the core JVM definition of arrays would be far more complex, and all implementations would be forced to provide this complexity at a low level;
  • there would be a "one-size fits all" resizing implementation in a given JVM, which might fail to satisfy many use-cases;
  • different implementations are likely to introduce large performance variances, which might need additional complicated constraint definition;
  • it introduces thread-safety issues around bounds-checking the array, because a.length becomes mutable;
  • additional linguistic support for expressing expansion => larger language;
  • performance implications for array subscripting, potential lack of O(1) indexing;
  • unfamiliar territory for C and C++ programmers, who are used to non-extensible arrays (or having such mechanisms provided in libraries);
  • casting in stone a variable-length mechanism already adequately handled by higher-level structures (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.

Emmaline answered 7/3, 2016 at 15:32 Comment(0)
C
1

That's in the definition of Java arrays:

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.

Cheltenham answered 7/3, 2016 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.