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?
The byte keyword is a data type that can store whole numbers from -128 to 127.
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.
To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With