Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Timothy Boland
Timothy Boland
18,237 Points

Android Activity Lifecycle | Creating the Adapter | Just curious why not start with int i = 1 instead of i = 0

I noticed you prefer to increment the for loop with:

    for (int i = 0; i < mHoles.length; i++) {
        mHoles[i] = new Hole("Hole" + (i + 1) + " :" +, strokes);
    }

I prefer to start with 1 like this, so I wont have to do the +1 later...and so its clear from the beginning whether , I truly am starting count by 0 or 1 with the data Im using

    for (int i = 1; i <= mHoles.length; i++) {
        mHoles[i] = new Hole("Hole" + (i) + " :" +, strokes);
    }

Is your way better? Is there a performance-gain im not aware of? Or a reason for this as a best practice?

1 Answer

J.D. Sandifer
J.D. Sandifer
18,813 Points

Arrays are generally indexed starting with 0. I.e. array[0] is the first item and array[1] is the second.

Both styles you show would loop the same number of times, but the second hits an "array out of bounds" exception if you just do mHoles[i]. The line needs to be like this:

mHoles[i-1] = new Hole("Hole" + (i) + " :" +, strokes);

Since mHoles[length-1] is the last slot in the array.

As you can see, in an example where the array slots need to hold numbers starting with 1, you end up either adding 1 to the index to get the number or subtracting 1 from the index to get the slot since array[0] holds 1, array[1] holds 2, etc. Either way can make sense in that case.

However, there are a lot of times where you just want to loop through an array and then it makes less sense to keep writing array[index-1] when you aren't also trying to count up from 1.

Thus, for consistency it can make sense to always start with index = 0.

(That being said, I believe there is at least one language that accesses arrays starting at index 1 which solves that problem. Unless you want to count up from 0...)