使用字节数组作为 Map 键 [英] Using a byte array as Map key
本文介绍了使用字节数组作为 Map 键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您认为使用字节数组作为 Map 键有什么问题吗?我也可以做 new String(byte[])
和 String
散列,但使用 byte[]
更直接.
Do you see any problem with using a byte array as Map key? I could also do new String(byte[])
and hash by String
but it is more straightforward to use byte[]
.
推荐答案
问题在于byte[]
使用对象标识来表示equals
和hashCode代码>,这样
The problem is that byte[]
uses object identity for equals
and hashCode
, so that
byte[] b1 = {1, 2, 3}
byte[] b2 = {1, 2, 3}
不会在 HashMap
中匹配.我看到三个选项:
will not match in a HashMap
. I see three options:
- 包装在
String
中,但是您必须注意编码问题(您需要确保字节 -> 字符串 -> 字节为您提供相同的字节). - 使用
List
(可能会占用大量内存). - 做自己的包装类,编写
hashCode
和equals
来使用字节数组的内容.
- Wrapping in a
String
, but then you have to be careful about encoding issues (you need to make certain that the byte -> String -> byte gives you the same bytes). - Use
List<Byte>
(can be expensive in memory). - Do your own wrapping class, writing
hashCode
andequals
to use the contents of the byte array.
这篇关于使用字节数组作为 Map 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文