Coffemanz
Coffemanz

Reputation: 953

Check if a list of byte arrays contains a new byte array

I have a list of byte arrays and need to check if this list doesn't contain a new given byte array. If not, than I need to perform some action.

Right now, I'm trying to do it like this:

List<byte[]> listOFByteArrays = getListOfByteArrays();
byte[] newByteArray = getNewByteArray();

if (!listOfByteArrays.contains(newByteArray)){
// do some action
}

This doesn't work for me, it performs this some action in the if statement anyway.

What am I doing wrong and what is the right way to check it?

Thank you in advance.

Upvotes: 1

Views: 3119

Answers (4)

Mwak
Mwak

Reputation: 104

Java's .contains(T) simply performs an equality check on the argument. An array, however, is not equal to another array containing the same values, because all of the values are not checked and the comparison is done on their pointers.

As you already have two byte[], the gruesome - but functional - way could be to simply... Iterate through the list, and use java.util.Arrays.equals(), which works wonders on primitive arrays.

List<byte[]> listOFByteArrays = getListOfByteArrays();
byte[] newByteArray = getNewByteArray();
boolean flag = false;

for(byte[] b : listOFByteArrays) {
    if(Arrays.equals(b,newByteArray)) { 
       flag = true; 
       break;
    }
}

if (!flag){
   // do stuff
}

Upvotes: 1

Vladimir Belanov
Vladimir Belanov

Reputation: 31

You can try this

if (!listOFByteArrays
    .stream()
    .anyMatch(byteArray -> Arrays.areEqual(byteArray, newByteArray))) {

    // do some action
}

Upvotes: 1

Ruslan
Ruslan

Reputation: 6290

List.contains method use equals to check if the list contain specific element. From javadoc:

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that Objects.equals(o, e).

But for arrays the equals method is the same as ==. That's why contains returns false even if content is the same. Use Arrays.equals instead:

for (byte[] arr : listOfByteArrays) {
    if (Arrays.equals(arr, newByteArray )) {

    }
}

Upvotes: 1

Pavel Smirnov
Pavel Smirnov

Reputation: 4799

You're looking for:

for (int i = 0; i < listOfByteArrays.size(); i++) {
    if (Arrays.equals(newByteArray, listOfByteArrays.get(i))) {
        //do some action
    }
}

Upvotes: 0

Related Questions