简体   繁体   English

如何在Java中的hashmap或hashtable中存储字节数组

[英]How to store bytearrays in hashmap or hashtable in java

Hi i have bytearrays of size 8 bytes each and i need to store them in a hashmap or hashtable. 嗨,我每个字节数组的大小为8个字节,我需要将它们存储在哈希表或哈希表中。 For example say i have 1000 blocks... then it will store 1st key and value(bytearray) and then when block2 is passed it should check if it is already present in hahtable and if not there it should increment and count should be incremented. 例如说我有1000个块...然后它将存储第一个键和value(bytearray),然后在传递block2时,应检查hahtable中是否已存在它,如果不存在,则应递增并计数。 I have written code to store but the problem is that it is not able to search, may be bacuse of the way i'm storing in byte array. 我已经写了代码来存储,但是问题是它无法搜索,可能是因为我在字节数组中存储的方式。

Code: 码:

int collisions = 0;
Hashtable<Integer, Long> ht = new Hashtable<Integer, Long>();
// Given bloc1 value here
if(ht.contains(bloc1)) {
  collisions++;
}
else {
  ht.put(i,ByteBuffer.wrap(bloc1).getLong());
}  

Problem is: ht.contains is not giving the desired o/p 问题是:ht.contains没有提供所需的o / p

byte[] objects, and other array objects in Java has equals() method inherited from Object , ie comparing by reference, not by array contents. byte[]对象和Java中的其他数组对象具有从Object继承的equals()方法,即通过引用而不是通过数组内容进行比较。

The simpliest way to resolve your problem (without additional dependencies to libraries) is to store 8-byte arrays as long s: 解决问题的最简单方法(不附加依赖库)是将8字节数组存储为long s:

Map<Long, Value> map = new HashMap<>();
...
// map.put(byteArray, value);
map.put(ByteBuffer.wrap(byteArray).getLong(), value);

Solution: int collisions = 0; 解决方案:int冲突= 0; Hashtable ht = new Hashtable(); Hashtable ht = new Hashtable(); // Given bloc1 value here if(ht.contains(ByteBuffer.wrap(bloc1).getLong())) {collisions++;} else { ht.put(i,ByteBuffer.wrap(bloc1).getLong()); //这里给定bloc1值if(ht.contains(ByteBuffer.wrap(bloc1).getLong())){collisions ++;} else {ht.put(i,ByteBuffer.wrap(bloc1).getLong()); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM