I would like to tell if the next line is different from the current line or this is the last line.
Is that sure that I won’t get an ArrayIndexOutOfBoundsException if I use this code?
And is it a good way to check this?
for (current_line = 0; current_line < lines_array.length; current_line++) {
/* ... */
boolean nextLineIsDifferentOrThereIsNoNextLine =
(current_line + 1 >= max_lines) ? true :
!lines_array[current_line].equalsIgnoreCase(lines_array[current_line + 1]);
/* ... */
}
edit:
I’ve tried it with a small array and I didn’t get any exceptions. How could it be? :S
If
max_linesis equal tolines_array.length, then it will work perfectly fine. Just add a one-line comment to clarify things (although the name of the variable makes it pretty clear)current_line + 1 >= maxLinesmakes sure you don’t get anArrayIndexOutOfBounds.Perhaps it is worth noting that there must be no
nullentries in the array, otherwise you risk aNullPointerException. So in order not to clutter your code, you can make a private method:And then have: