Why use parallel arrays in Java?

Is there any real use case for parallel arrays in Java? It seems too cumbersome to support N arrays that are interconnected.

Example:

int  ages[]   = {0,          17,        2,          52,         25};
String names[] = {"None",    "Mike",    "Billy",    "Tom",      "Stan"};
int  parent[] = {0,          3,         1,          0,          3};

I can just create a Person class and store the objects in one array. Will be a little more expensive but very easy to use?

+5
source share
4 answers

Parallel arrays are a break in languages ​​such as Basic (source) that did not have any data structures other than arrays. You should define the objects as you suggest, instead.

+10
source

Java - () IMO, / . 3 , .

, , , . - .

+11

/, , , .

Hash Maps is another solution. For example, instead of heterogeneous arrays for ages and names, if the names are unique, you can use the name as keys and age as a value.

+1
source

Classes are more pleasant, but if the use case is limited, for example. one method of the body, it is wasteful to create it. If you have a Pair class , you can specialize in it without creating a new class.

+1
source

All Articles