Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java set of byte arrays

Tags:

java

set

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?

like image 573
Jack Edmonds Avatar asked Jun 29 '10 02:06

Jack Edmonds


People also ask

What is byte [] in Java?

The byte keyword is a data type that can store whole numbers from -128 to 127.

How do you assign a byte value in Java?

byte Syntax in JAVA:byte Variable_Name = Value; For example: byte x = 10; Here x is variable name and 10 is a value assigned to a variable integer data type byte.

How do I combine byte arrays?

To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.

What is byte array example?

A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.


1 Answers

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

like image 188
Kevin Bourrillion Avatar answered Nov 16 '22 01:11

Kevin Bourrillion