[英]HashMap dont stay stable in android
嗨我想在HashMap中保存一個對象,如果它不存在,那么如果它是exsit我想用新數據控制它的值。 如果數據發生變化而不是我想做的...... 其他。 但每當我試圖比較新數據和哈希值時,我發現它們每次都是相同的。 我該如何處理這個問題。 有代碼:
BluetoothLeDevice deviceLe;
private Map<String, byte[]> mMacMap;
byte [] integer0 =new byte[4];
byte[] tempInteger0=new byte[4];
public void addSensor(String macId, BluetoothLeDevice deviceLe) {
byte [] addSensorrecord=deviceLe.getScanRecord();
int j=0;
for(int i=15;i<19;i++)
{
integer0 [j]=addSensorrecord[i];
j++;
}
if (mMacMap.containsKey(macId)) {
tempInteger0 = mMacMap.get(macId);
if(!integer0 .equals(tempInteger0))
{
mMacMap.remove(macId);
mMacMap.put(macId, integer0 );
new SendBLEData().execute(deviceLe);
}
} else {
final byte [] LocalInteger0=new byte[4];
int t=0;
for(int i=15;i<19;i++)
{
LocalInteger0[t]=addSensorrecord[i];
t++;
}
mMacMap.put(macId, LocalInteger0);
new SendBLEData().execute(deviceLe);
}
}
我猜,你的問題在這里:
!Integer0.equals(tempInteger0))
我想你想比較兩個數組; 你會驚訝地發現它們總是與眾不同......
您的問題是:數組上的equals()不會對數組內容進行比較。 換句話說:如果你要比較的數組是一個且相同的話,這個對equals()的調用只給出“true”,如:
int a[] = { 1 };
int b[] = a;
int c[] = { 1 };
這里:
a.equals(b) --> true
但
a.equals(c) --> false
在比較數組內容時,您應該使用ArrayList。 因為兩個ArrayList對象在包含完全相同的相等元素時是相等的 。
你會看到:你在數組上使用等於你的代碼做出決定。 所以,你要么改為ArrayLists; 或者使用Arrays.equals()作為用戶hamsty建議。
只是添加了已經發布的答案。
刪除下面沒有必要,簡單的put將替換舊值
mMacMap.remove(macId);
mMacMap.put(macId, integer0 );
來自javadoc
如果映射先前包含鍵的映射,則舊值將替換為指定的值。 (當且僅當m.containsKey(k)返回true時,地圖m才包含密鑰k的映射。)
您是否考慮將字節15-19轉換為字符串並將其添加到地圖鍵中? 這將消除陣列比較並使查找更快。
!Integer0.equals(tempInteger0))
是你的問題。
用它來比較數組的內容:
Arrays.equals(Integer0, tempInteger0)
問題是以下一系列事件:
macId
不在mMacMap
,插入new byte[4];
進入地圖 macId
中的mMacMap
,由於其他答案提到的數組比較問題,上一步創建的數組永遠不會匹配integer0
,使用對macId
的引用替換地圖中的integer0
macId
中的mMacMap
,因為該數組是對integer0
的引用,它將始終進行正比較,並且內容將不再更新。 基本上由這兩個問題引起:
Array#equals
行為不直觀,使用靜態方法Arrays.equals
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.