2012-11-15 19 views
0

我添加了一些键值对的散列映射。在我添加键值对之后,当我打印hashmap的大小时,我得到的大小为1.当我在另一个地方打印值(向key-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 
} 
     } 
+2

你'mHashMapCallbacks'领域不是一成不变的。你确信你的班级的同一个实例*正在打印零消息吗? –

+0

是在'receiveMessage()'之前调用'startTimeServer()'。 – PermGenError

+0

ICommonResultCallback.Stub - 这是一个静态的内部类?如果是这样,那么它不能访问外部类变量 –

回答

1

ICommonResultCallback()看起来像一个回调函数。如果是这样,那么当调用这个函数时,hashmap将被重新初始化。这是因为您创建了一个新的实例类,用于回叫。

你可以通过使用hashmap“static”来验证这一点。它应该保留这个价值。

1

常见的Java基础

private HashMap <Context,BLEEventListeners> mHashMapCallbacks = new HashMap<Context,BLEEventListeners>(); 

这里语境是你的钥匙,其必须是唯一的,否则每次一个HashMap中不包含您的数据,如果你只用不用你为什么听者列表或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 
    } 
      }