Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use parallel arrays in Java?

Is there any real use case for parallel arrays in Java? It seems too cumbersome to maintain N arrays which are interrelated.

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 class Person and store objects in one single array. Will be little more expensive, but much easy to use right?

like image 888
zengr Avatar asked Mar 18 '11 02:03

zengr


People also ask

When should parallel arrays be used?

Parallel arrays come in handy when data regarding different characteristics of the same subject of interest needs to be stored and accessed efficiently. The diagram below shows two parallel arrays. The first array stores product names, and the second array stores the price of each product.

What are the advantages of parallel arrays over the traditional arrays?

Which of the following is an advantage of parallel arrays? Explanation: Elements in the parallel array are accessed sequentially as one arrays holds the keys whereas other holds the values. This sequential access generally improves Locality of Reference. It is an advantage.

What are the limitations of parallel arrays?

Parallel arrays may be arbitrarily composed with indexed arrays and records, but they cannot be nested inside of other parallel arrays, i.e., the elements of a parallel array cannot be a parallel array. The rank of a parallel array is its number of dimensions.

Do parallel arrays need the same data type?

Notice that the arrays do not all contain the same "type" of data. It is often necessary to represent data in a "table" form, as shown below. Such data, can be stored using parallel arrays. Parallel arrays are several arrays with the same number of elements that work in tandem to organize data.


1 Answers

The only real advantage of parallel arrays in Java is as an (IMO extreme) measure to reduce object allocation and / or heap usage. For a large enough collection of objects, 3 arrays will occupy less space AND use fewer objects than a single array of instances of some custom class.

This approach is normally a bad idea, since it makes your code a lot more fragile. Creating and using a custom class is the best approach in most situations.

Note: the Performance Tips for Android advise otherwise, but those tips are primarily focused on reducing the frequency / impact of GC pauses on user experience. And even that advice is caveated in a couple of ways.

like image 124
Stephen C Avatar answered Oct 21 '22 05:10

Stephen C