且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数据存储到哈希表中-Java

更新时间:2023-01-06 22:43:20

int id = 1;-您永远不会更改此设置,因此您要做的就是每次都替换ID 1的条目.您需要一个唯一的ID生成器,或者只需要在每次添加条目时递增id.

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.

正如评论者正确指出的那样,您应该使用HashMap而不是HashTable,并且您真的不应调用方法Hashtable ...

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

好,您更改了代码示例,因此不再准确,但是现在发生的情况是DeviceID不存在,因此您得到-1或保持获取相同的设备ID.当然,您说要存储来自同一设备的多条消息,因此您自己不想使用设备ID.您可能应该改用某种消息ID,最有可能在设备上生成,并以某种方式合并设备ID以确保其唯一性.

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.