无法检索以前提取的HashMap数据

时间:2015-01-12 22:55:56

标签: java hashmap

我有一个方法可以每5秒循环一次从websever抓取的数据数组。

一切正常,但值永远不会更新,即使在先前的提取中添加了key,也始终保持添加,这意味着

int value = myHashMapDB.get(key);

value始终返回null

来自服务器的数组中的

keys始终是唯一的。

   private HashMap<String,Integer> myHashMapDB;

//call this method every five seconds
private void getFromSeverEveryFiveSeconds() {

     HashMap<String,Integer> myHashMapTEMP = new HashMap<String, Integer>(); //declare/clear previous data 

    //use async and fetch some data from server with a unique key for each row        
     JSONObject json = fetchSomeDataJson();
     JSONObject cars = json.getJSONObject("cars");
     for (int i = 0; i < 200; i++) {
         String key = cars.names().getString(i); //get key from JSON array fetched from server

         if(myHashMapDB != null){ //skip first time
             //ok, this not the first time so check if key exists from previous fetch

             int value = myHashMapDB.get(key);
             if(value != null){
                value = updateValue; //update value
                myHashMapTEMP.put(key,value); //put the value with the same key
                continue; //go to next loop
             }
         }


         //ok, key does not exists, add it

         int value = newValue;
         myHashMapTEMP.put(key,value); //put it with the key
     }

     //ok loop is done, lets finalize data

     if(myHashMapDB != null && myHashMapDB.size() != 0){ //if this is not the first time
         for (int value : myHashMapDB.values()) {
                //remove old ones. works fine!
         }
     }

     myHashMapDB = new HashMap<String, Integer>(); //declare/clear previous data
     myHashMapDB.putAll(myHashMapTEMP); //copy all the data from current loop to the main HashMap.
     myHashMapTEMP = null; //clear the temporary HashMap data
}

以下是没有评论的源代码

private HashMap<String,Integer> myHashMapDB;

private void getFromSeverEveryFiveSeconds() {
     HashMap<String,Integer> myHashMapTEMP = new HashMap<String, Integer>();

     JSONObject json = fetchSomeDataJson();
     JSONObject cars = json.getJSONObject("cars");

     for (int i = 0; i < 200; i++) {
         String key = cars.names().getString(i);

         if(myHashMapDB != null){
             int value = myHashMapDB.get(key);
             if(value != null){
                value = updateValue;
                myHashMapTEMP.put(key,value);
                continue;
             }
         }

         int value = newValue;
         myHashMapTEMP.put(key,value); 
     }

     if(myHashMapDB != null && myHashMapDB.size() != 0){
         for (int value : myHashMapDB.values()) {
                //remove old ones. works fine!
         }
     }

     myHashMapDB = new HashMap<String, Integer>();
     myHashMapDB.putAll(myHashMapTEMP);
     myHashMapTEMP = null;
}

示例JSON数据

{"totalcars":1,"cars":{"C87ED7":["????","","MAZDA","R8",-46.1685,167.833,0,0,0,"1421104212","0000",0,""]}}

使用上面的示例数据C87ED7将是关键。

0 个答案:

没有答案