user
user

Reputation: 6797

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 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

Upvotes: 0

Views: 531

Answers (3)

Carlos
Carlos

Reputation: 2513

Looks okay to me, assuming that your array does not contain null values.

Upvotes: 0

Bozho
Bozho

Reputation: 597076

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];

Upvotes: 2

Garis M Suero
Garis M Suero

Reputation: 8170

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.

Upvotes: 1

Related Questions