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

查看:21
本文介绍了使用字节数组作为 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[] 使用对象标识来表示equalshashCode,这样

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:

  1. 包装在 String 中,但是您必须注意编码问题(您需要确保字节 -> 字符串 -> 字节为您提供相同的字节).
  2. 使用List(可能会占用大量内存).
  3. 做自己的包装类,编写hashCodeequals来使用字节数组的内容.
  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天全站免登陆