Programming Java: the Limitations of Arrays - dummies

Programming Java: the Limitations of Arrays

By Barry Burd

Arrays in Java are nice, but they have some serious limitations. Imagine that you store customer names in some predetermined order. Your code contains an array, and the array has space for 100 names.

String name[] = new String[100];
for (int i = 0; i < 100; i++) {
    name[i] = new String();

All is well until, one day, customer number 101 shows up. As your program runs, you enter data for customer 101, hoping desperately that the array with 100 components can expand to fit your growing needs.

No such luck. Arrays don’t expand. Your program crashes with an ArrayIndexOutOfBoundsException.

“In my next life, I’ll create arrays of length 1,000,” you say to yourself. And when your next life rolls around, you do just that.

String name[] = new String[1000];
for (int i = 0; i < 1000; i++) {
    name[i] = new String();

But during your next life, an economic recession occurs. Instead of having 101 customers, you have only 3 customers. Now you’re wasting space for 1,000 names when space for 3 names would do.

And what if no economic recession occurs? You’re sailing along with your array of size 1,000, using a tidy 825 spaces in the array. The components with indices 0 through 824 are being used, and the components with indices 825 through 999 are waiting quietly to be filled.

One day, a brand-new customer shows up. Because your customers are stored in order (alphabetically by last name, numerically by Social Security number, whatever), you want to squeeze this customer into the correct component of your array. The trouble is that this customer belongs very early on in the array, at the component with index 7. What happens then?

You take the name in component number 824 and move it to component 825. Then you take the name in component 823 and move it to component 824. Take the name in component 822 and move it to component 823.

You keep doing this until you’ve moved the name in component 7. Then you put the new customer’s name into component 7. What a pain! Sure, the computer doesn’t complain. But as you move around all these names, you waste processing time, you waste power, and you waste all kinds of resources.

“In my next life, I’ll leave three empty components between every two names.” And of course, your business expands. Until, eventually you find that three aren’t enough.