簡體   English   中英

如何在Java中的hashmap或hashtable中存儲字節數組

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

嗨,我每個字節數組的大小為8個字節,我需要將它們存儲在哈希表或哈希表中。 例如說我有1000個塊...然后它將存儲第一個鍵和value(bytearray),然后在傳遞block2時,應檢查hahtable中是否已存在它,如果不存在,則應遞增並計數。 我已經寫了代碼來存儲,但是問題是它無法搜索,可能是因為我在字節數組中存儲的方式。

碼:

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());
}  

問題是:ht.contains沒有提供所需的o / p

byte[]對象和Java中的其他數組對象具有從Object繼承的equals()方法,即通過引用而不是通過數組內容進行比較。

解決問題的最簡單方法(不附加依賴庫)是將8字節數組存儲為long s:

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

解決方案:int沖突= 0; Hashtable ht = new Hashtable(); //這里給定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