tags:

views:

60

answers:

4

I have a HashSet of byte[]s and I would like to test whether a new byte[] is in that set. The problem is that Java seems to be testing whether the byte[] instances are the same rather than testing whether the actual values in the byte arrays are the same.

In other words, consider the following code:

public class Test
{
    public static void main(String[] args)
    {
        java.util.HashSet<byte[]> set=new java.util.HashSet<byte[]>();
        set.add(new String("abc").getBytes());
        System.out.println(set.contains(new String("abc").getBytes()));
    }
}

This code prints out false and I would like it to print out true. How should I go about doing this?

+1  A: 

You could define your own wrapper class, but probably the easiest thing to do is to "wrap" the arrays into ArrayLists and use a HashSet<ArrayList>.

GregS
+1  A: 

You could create a ByteArray class that wraps the byte arrays and tests for equality the way you want. Then you'd have a Set<ByteArray>.

Adam Crume
+5  A: 

Read this article named Java theory and practice: Hashing it out Defining hashCode() and equals() effectively and correctly
Then what I would do is create a wrapper class that would have an overridden hashCode() calculated from the values in the byte[]

Romain Hippeau
+1 (the excellent reference almost deserves a +1 by itself).
Pascal Thivent
+1  A: 

You can wrap each byte array using ByteBuffer.wrap, which will provide the right equals and hashCode behavior for you. Just be careful what methods you call on the ByteBuffer (that you don't modify the array or advance its pointer).

Kevin Bourrillion