Check if the next array element is different from the current in Java
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 anArrayIndexOutOfBoundsException
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开发者_如何学JAVA 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_lines
is equal to lines_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 >= maxLines
makes sure you don't get an ArrayIndexOutOfBounds
.
Perhaps it is worth noting that there must be no null
entries in the array, otherwise you risk a NullPointerException
. So in order not to clutter your code, you can make a private method:
private boolean itemsDiffer(String current, String next) {
if (current == null && next == null {
return false; // or true, if that's your semantics
} else {
return current == null || current.equalsIgnoreCase(next);
}
}
And then have:
boolean nextLineIsDifferentOrThereIsNoNextLine =
(current_line + 1 >= max_lines) ? true :
itemsDifferent(linesArray[current_line], linesArray[current_line + 1];
Why don't just iterate it in it's natural order, i mean you don't have to compare it with the next array, just compare it with the previous one.
Looks okay to me, assuming that your array does not contain null values.
精彩评论