0

so i have a list List<byte[]> lets say "fullList", whereby some other piece of code generates another List containing some byte[] partialList. so i use the .contain method which always fails for searching got byte[] in partialList from the fullList. Why is this??

List<byte[]> fullList = {some byte[] arrays added here..}
List<byte[]> partialList = {some byte[] arrays added here..}

byte[] toCheck = partialList.get(0);
System.out.println("The check is "+ fullList.contains(tocheck));
Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
Fuzel Jamil
  • 23
  • 1
  • 6
  • Because it isn't in the list? – Scott Hunter Nov 10 '14 at 15:38
  • i know the byte[] should be in the list. i am generating them both. – Fuzel Jamil Nov 10 '14 at 15:39
  • You generate the two lists using different pieces of code. Then pull out on element and ask if it is in a *third* list (`leafs`). And provide *no* information as to what is in *any* of these lists. – Scott Hunter Nov 10 '14 at 15:41
  • sorry, renamed it. the lists contain hashes of some xml document parsed using jaxb. – Fuzel Jamil Nov 10 '14 at 15:45
  • Unless I'm mistaken, Java arrays don't implement `equals` properly, thus two `byte[]` will only be considered equal if they are the exact same object reference. If those are hashed, try encoding those `byte[]` as `Integer` or `Long`. – tobias_k Nov 10 '14 at 15:45
  • so how could i achieve this kind of equality check for byte[]. is searching the whole list everytime my only option? – Fuzel Jamil Nov 10 '14 at 15:47

1 Answers1

5

The problem is that Java arrays do not implement equals properly, i.e. two arrays are considered "equal" only if their memory address is the same, i.e. if they are the exact same object reference.

byte[] foo = {1,2,3};
byte[] bar = {1,2,3};
System.out.println(foo.equals(bar)); // prints 'false'

To work around this problem, you could either encode those byte[] as numbers and use List<Integer> (or Long) instead, or implement your own contains method using Arrays.equals

boolean contains(List<byte[]> arrays, byte[] other) {
    for (byte[] b : arrays)
        if (Arrays.equals(b, other)) return true;
    return false;
}
Community
  • 1
  • 1
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • So after for every sha-256 hash i get (which i populate the list with) i encode it to some numbers. Ok thanks.. – Fuzel Jamil Nov 10 '14 at 15:58