When NOT to use Java’s array.length method!

Starbucks cups

I know it's cliche using my coffee cup photo here because I'm talking about Java, but I hate blog posts without at least one picture you must understand. Thank you.

A few days ago I posted a beginners problem I was having with Java related to counting how many elements there are in an array; seems basic right?

Here's an example of what I was doing:

for (count = 0; count < arrayThing.length; count++) {
   grandTotal += arrayThing[count].getAmount;
}

As Mark so graciously pointed out for me, I was guilty of a logic error by incorrectly using the length method to determine how many elements there were in the array. The length method returns the entire length of the array that was previously instantiated, NOT up until the index where there have stopped being values entered!

A way to get around this is to use a counter whenever you add a new item to array in a similar fashion to below, then using the counter in place of the length method whenever you need to loop through the values.

public void addToArray(int e) {
   this.arrayThing[nArrayThing] = e;
   nArrayThing++;
}

I was under the impression Java's for each statement could also have been used, but that's for use in collections not arrays.

Thanks to Mark for helping with my rusty Java knowledge :).