Link Search Menu Expand Document

Arrays

Table of Contents

  1. Proper Use of Arrays
  2. Unrolling Arrays

Proper Use of Arrays

Arrays can be used to store multiple values, but with great power comes great responsibility. Arrays should be used to store related values. They should not be used to store multiple independent values. For instance:

Bad
int[] numbers = new int[3];
System.out.print("What day of the month is it (1-31)? ");
numbers[0] = console.nextInt();
System.out.print("What is the temperature today? ");
numbers[1] = console.nextInt();
System.out.print("How old are you? ");
numbers[2] = console.nextInt();

This is an example of cramming a bunch of data into an array even though that data has nothing to do with each other.

On a similar note, sometimes it can make sense to return an array, but just because you can return an array doesn't mean you should use it as a way to hack returning multiple values from a method.

Unrolling Arrays

Often when using arrays, you need to access data from a certain range of indices (usually the entire array). To do this, you should always use a loop to traverse the indices of the array, rather than "unrolling" the array by manually accessing each index of the array. Even if you know exactly how many items are in your array, using a loop is better stylistically. It makes your code much more flexible; you could change the size of your array without having to change the way you access the array's elements!

Bad
This approach is what is referred to as unrolling an array, which is not the best way to access array elements
double[] temperatures = {32,41,39,58};

// BAD APPROACH: unrolling
double avgTemp1 = 0;
avgTemp1 += temperatures[0];
avgTemp1 += temperatures[1];
avgTemp1 += temperatures[2];
avgTemp1 += temperatures[3];
avgTemp1 = avgTemp / temperatures.length;
Bad
Even though it's all in one line, this approach is still manually unrolling the array and therefore inflexible
double avgTemp2 = temperatures[0] + temperatures[1] + temperatures[2] + temperatures[3];
avgTemp2 = avgTemp2 / temperatures.length;
Good
What you should do is an array traversal, like this
double avgTemp = 0;
for (int i = 0; i < numbers.length; i++) {
  avgTemp += temperatures[i];
}
avgTemp = avgTemp / temperatures.length;