Linkandzelda
Linkandzelda

Reputation: 611

Java: Arrays.equals not working

I have an array which is a byte[] of a file I've read in. I need to check the first 5 bytes of the file. To begin I did this:

if (ips_bytes[0] != ips_ident[0] && ips_bytes[1] != ips_ident[1] && ips_bytes[2] != ips_ident[2]
            && ips_bytes[3] != ips_ident[3] && ips_bytes[4] != ips_ident[4]) {
        return "Nope!";
    }

This works, but it doesn't look very nice and I guess it's not very efficient. So I looked into other methods and found Arrays.equals(). I changed my code to reflect that:

if (!Arrays.equals(ips_ident, Arrays.copyOfRange(ips_bytes, 0, 4))) {
        return "Baka";
    }

This didn't work, and I tried 0, 4 and 1, 5 to see if the ranges were different. Am I missing something because this looks right? The array values are definitely correct.

Upvotes: 0

Views: 884

Answers (3)

jahroy
jahroy

Reputation: 22692

Here's an approach that doesn't use unnecessary memory and is re-usable.

Just use a for loop:

public boolean compareFirstBytes(byte[] arrayOne, byte[] arrayTwo, int range) {
    for (int i = 0; i < range; i++) {
        if (arrayOne[i] != arrayTwo[i]) {
            return false;
        }
    }
    return true;
}

Upvotes: 1

RiaD
RiaD

Reputation: 47619

Your conditions are not equivalent.

First one will be true if all pairs of corresponding elements are not equal

The second will be true if exists at least one pair of elements that aren't equal

I believe you need the second code, but you need to fix it a bit. Arrays.copyOfRange's third parameter-index is exculeded. So you need

Arrays.copyOfRange(ips_bytes, 0, 5))

or better

Arrays.copyOfRange(ips_bytes, 0, ips_ident.length))

Upvotes: 6

Alex
Alex

Reputation: 11579

I suppose it should the same range of bytes:

if (!Arrays.equals(Arrays.copyOfRange(ips_ident, 0, 5), Arrays.copyOfRange(ips_bytes, 0, 5)))

Example

char[] arr1 = new char[] { 'a', 'b', 'c', 'd', 'e' };
char[] arr2 = new char[] { 'a', 'b', 'c', 'k', 'm' };
System.out.println(Arrays.equals(Arrays.copyOfRange(arr1, 0, 3), Arrays.copyOfRange(arr2, 0, 3)));

Upvotes: 1

Related Questions