Java字节数组

Jac*_*nds 8 java set

我有一个HashSet的byte[]s,我想测试一个新的byte[]是否在该集合中.问题是Java似乎在测试byte[]实例是否相同,而不是测试字节数组中的实际值是否相同.

换句话说,请考虑以下代码:

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()));
    }
}
Run Code Online (Sandbox Code Playgroud)

这个代码打印出来false,我希望它打印出来true.我应该怎么做呢?

Kev*_*ion 7

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


Jam*_*olk 1

您可以定义自己的包装类,但可能最简单的方法是将数组“包装”到 ArrayList 中并使用HashSet<ArrayList>.