code stench

Don’t iterate to find an index. Why? You already know the index.

int toFind = ...;
for (int i=0;i<array.length;i++) {
  if (i == toFind) {
    array[i].doSomething();
    break;
  }
}

Just use array[toFind].doSomething(). Iterate only when you are matching some other non-index attribute.

The same applies even if you have lists, or if you’re looking for toFind-1.

RSS feed for comments on this post · TrackBack URL

Leave a Comment