我在hashmap中添加了几个键值对。
在我添加键值对后,当我打印hashmap的大小时,我得到的大小为1.当我在另一个地方打印值时(在向key-hashmap添加值之后),我得到了hashmap的大小为零。我不会从此类或任何其他外部类中删除添加到此hashmap的值。那么,hashmap大小如何变为零?有人可以解释一下吗?
感谢任何帮助。
代码在这里:
private HashMap <Context,BLEEventListeners> mHashMapCallbacks = new HashMap<Context,BLEEventListeners>();
public void startTimeServer(BLEEventListeners eventListener,Context context) {
mHashMapCallbacks.put(context, eventListener);
Log.d(TAG,"****Inside startTimeServer,mHashMapCallbacks size: " +mHashMapCallbacks.size());// I get 1 as size
Intent cmn_intent = new Intent(IServerCommon.class.getName());
Intent time_intent = new Intent(ITimeServer.class.getName());
mContext.bindService(time_intent, time_connection, Context.BIND_AUTO_CREATE);
mContext.bindService(cmn_intent, cmn_connection, Context.BIND_AUTO_CREATE);
}
private ICommonResultCallback callback = new ICommonResultCallback.Stub() {
public void receiveMessage(Bundle value) throws RemoteException {
Log.d(TAG,"****Inside connected,mHashMapCallbacks size: " +mHashMapCallbacks.size());// I get 0 as size
}
}
答案 0 :(得分:1)
ICommonResultCallback()看起来像一个回调函数。如果是,则在调用此函数时将再次初始化hashmap。这是因为还为回调创建了一个新的Instance of class。
您可以使用hashmap“static”来验证这一点。然后应保留该值。
答案 1 :(得分:1)
Common Java Basics
private HashMap <Context,BLEEventListeners> mHashMapCallbacks = new HashMap<Context,BLEEventListeners>();
这里Context是你的密钥,每次一个hashmap不包含你的数据时必须是唯一的,如果你只使用了listener,你为什么不使用List或ArrayList,
仍然你必须用上下文做一些像这样的事情
private ArrayList<HashMap> tempArray = new ArrayList<HashMap>();
public void startTimeServer(BLEEventListeners eventListener,Context context) {
HashMap <Context,BLEEventListeners> mHashMapCallbacks = new HashMap<Context,BLEEventListeners>();
tempArray.add(mHashMapCallbacks);
Log.d(TAG,"****Inside startTimeServer,mHashMapCallbacks size: " +mHashMapCallbacks.size());// I get 1 as size
Intent cmn_intent = new Intent(IServerCommon.class.getName());
Intent time_intent = new Intent(ITimeServer.class.getName());
mContext.bindService(time_intent, time_connection, Context.BIND_AUTO_CREATE);
mContext.bindService(cmn_intent, cmn_connection, Context.BIND_AUTO_CREATE);
}
private ICommonResultCallback callback = new ICommonResultCallback.Stub() {
public void receiveMessage(Bundle value) throws RemoteException {
Log.d(TAG,"****Inside connected,Array size: " +tempArray.size());// I get 0 as size
}
}