简体   繁体   中英

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. 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. 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

byte[] objects, and other array objects in Java has equals() method inherited from Object , ie comparing by reference, not by array contents.

The simpliest way to resolve your problem (without additional dependencies to libraries) is to store 8-byte arrays as long s:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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