Executing the following code:
public class Main {
public static void main(String[] args) {
Util util = new Util();
util.addBlock(1);
util.addBlocks(util.getBlocks());
}
}
public class Util {
public static HashMap<Long, Integer> blockMap = new HashMap<>();
private Gson gson = new Gson();
public void addBlocks(String json){
Map map = gson.fromJson(json, Map.class);
blockMap.putAll(map);
System.out.println(blockMap.keySet());
}
public void addBlock(int i){
blockMap.put(0L, i);
}
public String getBlocks(){
return gson.toJson(blockMap);
}
}
I get the output
[0, 0]
from the print System.out.println(blockMap.keySet());
.
So, for some reason, I have a Map<Long, Integer>
that contains two Long
s with value 0
as key. And a keyset Set<Long>
with two 0
s. But map and set do not allow duplicate keys, how is this possible?
The code first adds a simple entry to the map:
blockMap.put(0L, i);
Then, I add another entry by converting the map to a JSON string, using GSON and then back to a map:
gson.toJson(blockMap);
...
Map map = gson.fromJson(json, Map.class);
blockMap.putAll(map);
I would expect that it overwrites the previous entry and not adds another entry with the same, duplicate, key.