如何使Java Hashtable.containsKey适用于Array?

Jac*_*ack 7 java hashtable

很抱歉提出这个问题,但我是Java的新手.

Hashtable<byte[],byte[]> map = new Hashtable<byte[],byte[]>();
byte[] temp = {1, -1, 0};
map.put(temp, temp);
byte[] temp2 = {1, -1, 0};;
System.err.println(map.containsKey(temp2));
Run Code Online (Sandbox Code Playgroud)

不适用于.containsKey(因为打印结果为"False")

Hashtable<Integer,Integer> mapint = new Hashtable<Integer, Integer>();
int i = 5;
mapint.put(i, i);
int j = 5;
System.err.println(mapint.containsKey(j));
Run Code Online (Sandbox Code Playgroud)

工作(打印结果为"True")

我知道它与对象引用有关,但搜索后无法达到任何解决方案...

反正我是否可以使用Hashtable查找具有Array类型的键?我只是想测试一个特定的数组是否在Hashtable中作为键...

任何点击都会很棒.谢谢!!!

Era*_*ran 6

你不能在a中使用数组作为键HashTable/HashMap,因为它们不会覆盖Object's 的默认实现equals,这意味着temp.equals(temp2)当且仅当temp==temp2,在你的情况下不是这样.

您可以使用Set<Byte>List<Byte>代替a byte[]来代替您的密钥.

例如 :

Hashtable<List<Byte>,Byte[]> map = new Hashtable<List<Byte>,Byte[]>();
Byte[] temp = {1, -1, 0};
map.put(Arrays.asList(temp), temp);
Byte[] temp2 = {1, -1, 0};;
System.err.println(map.containsKey(Arrays.asList(temp2)));
Run Code Online (Sandbox Code Playgroud)