使用一个字节数组作为Map键 [英] Using a byte array as Map key

查看:112
本文介绍了使用一个字节数组作为Map键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你看到使用一个字节数组作为Map键有什么问题吗?我也可以通过 String 执行 new String(byte [])和hash,但使用<$更直接c $ c> byte [] 。

解决方案

问题在于对于等于 hashCode ,byte [] 使用对象标识,所以

  byte [] b1 = {1,2,3} 
byte [] b2 = {1,2,3}

HashMap 中不匹配。我看到了三个选项:


  1. 包装在字符串中,但您必须请注意编码问题(您需要确保字节 - >字符串 - >字节为您提供相同的字节)。
  2. 使用 List< Byte> / code>(在内存中可能很贵)。
  3. 创建自己的包装类,写 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:

  1. 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).
  2. Use List<Byte> (can be expensive in memory).
  3. Do your own wrapping class, writing hashCode and equals to use the contents of the byte array.

这篇关于使用一个字节数组作为Map键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆