how to keep data stored into a hashtable - java

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 04:54:09

问题


I have a Socket server waiting for the clients send messages in a json format. I do not need to store the data into database, but for now, I would like to keep them in a hashtable. So, when the client sent a message the server will add it to the hashtable without losing the previous messages.

Here is the declaration of my hashtable:

private static Hashtable<Integer,String> table = new Hashtable<Integer,String>();

Here is the method that is called a message reach the server:

    private void HashTable(String string){
    //JsonArray questions =  new JsonArray();
    //questions = string;
    //for(int i = 0; i < questions.length(); i++) {
        //JsonObject question = questions.getJsonObject(i);
        JSONObject jsonObj;
        try {
            jsonObj = new JSONObject(string);
            int id = jsonObj.optInt("DeviceID", -1);
            String name = jsonObj.toString();
            table.put(id, name);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    //}
}

The code above is not keeping the data from the previous messages. Could anybody give a hint?

thank you


回答1:


int id = 1; - you never change this, so all you are doing is replacing the entry for ID 1 each time. You need either a unique ID generator or just to increment id every time an entry is added.

Edit: As the commenters rightly point out, you should be using HashMap not HashTable, and you really shouldn't be calling your method Hashtable...

Edit 2: Well you changed the code sample so this is no longer accurate, but now what's happening is either DeviceID doesn't exist so you get -1 or you keep getting the same device ID. Of course, you say you want to store multiple messages from the same device, so using a device ID on it's own isn't what you want to do. You should probably have some sort of message ID instead, most likely generated on the device and somehow incorporating the device ID to help ensure it's unique.




回答2:


Thats because , when the "DeviceId" is null from the Json , you will always end up storing with the same key "1". Hence it replaces the old value.

Solution

private static AtomicInteger count = new AtomicInteger ;

in the place where you insert into hashtable adapt to

int id = jsonObj.optInt("DeviceID", count.addAndGet(1) );


来源:https://stackoverflow.com/questions/15233102/how-to-keep-data-stored-into-a-hashtable-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!