使用一个字节数组作为Map键 [英] Using a byte array as Map key
本文介绍了使用一个字节数组作为Map键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你看到使用一个字节数组作为Map键有什么问题吗?我也可以通过 String
执行 new String(byte [])
和hash,但使用<$更直接c $ c> byte [] 。
解决方案
问题在于对于
使用对象标识,所以等于
和 hashCode
,byte []
byte [] b1 = {1,2,3}
byte [] b2 = {1,2,3}
在 HashMap
中不匹配。我看到了三个选项:
- 包装在
字符串
中,但您必须请注意编码问题(您需要确保字节 - >字符串 - >字节为您提供相同的字节)。
- 使用
List< Byte> / code>(在内存中可能很贵)。
- 创建自己的包装类,写
hashCode
和equals
来使用字节数组的内容。
- 创建自己的包装类,写
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[]
.
解决方案
The problem is that byte[]
uses object identity for equals
and hashCode
, so that
byte[] b1 = {1, 2, 3}
byte[] b2 = {1, 2, 3}
will not match in a HashMap
. I see three options:
- 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屋!
查看全文