java hashmap seems to allow 2 duplicate keys

Related searches

Executing the following code:

public class Main {

    public static void main(String[] args) {
        Util util = new Util();


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);

    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 Longs with value 0 as key. And a keyset Set<Long> with two 0s. 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:

Map map = gson.fromJson(json, Map.class);

I would expect that it overwrites the previous entry and not adds another entry with the same, duplicate, key.

java hashmap seems to allow 2 duplicate keys, A quick and practical guide to handling duplicate keys by using 2. Standard Maps. Java has several implementations of the interface Map, each one with its own particularities. However, none of the existing Java core Map implementations allow a Map<String, List<String>> map = new HashMap<>();. Java HashMap doesn't allow the the duplicate key but it allows the duplicate value. what does it mean that it doesn't allow duplicate. How it internally checks the key is duplicate, any guess? Here people think that internally HashMap would have checked in the existing key that it already there or not.

The issue here is as @Zabuza pointed out, that you are using a raw Map without generics that are erased at runtime. Just try out this example:

for (Object key: Util.blockMap.keySet()) {
    System.out.println("key: " + key + " type: " + key.getClass());

and you will see that your first key is of type Long while the second key is of type String

Since the equals-method is defined inside String as:

if (anObject instanceof String) {
    // ...
return false;

equals will always return false

How to Store Duplicate Keys in a Map in Java?, Java Collections allows you to add one or more elements with the MultiValueMap; public class MultiHashMapExample { public static void multiple keys, using the org.apache.commons.collections seems to be a From http://e-� Java HashMap. In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and you have to access them with an index number (int type). A HashMap however, store items in "key/value" pairs, and you can access them by an index of another type (e.g. a String). One object is used as a key (index) to another object (value).

I hope the following code will clear your doubt:

public void addBlocks(String json) {
    Map map = gson.fromJson(json, Map.class);
    Iterator itr=blockMap.keySet().iterator();

Output with this code:

[0, 0]
class java.lang.Long
class java.lang.String

Allowing Duplicate Keys in Java Collections, Learn to join hashmaps in two cases - ignore duplicate keys (overwrite values) or handle duplicate keys using Java 8. As we know hashmap does not allow duplicate keys. 2. Java 8 combine two hashmaps – handle duplicate keys. If we want to handle [/java] tags otherwise code may not appear partially or even fully. The HashMap is a class that implements the Map interface. It is based on the Hash table. It allows null values and null keys. You can store key-value pairs in the HashMap object. Once you do so you can retrieve the values of the respective keys but, the values we use for keys should be unique. Duplicate values

How to join or merge two hashmaps in Java, 2. Java HashMap Features � HashMap cannot contain duplicate keys. � HashMap allows multiple null values but only one null key. � HashMap is an unordered� Description: Below example shows how to avoid duplicate user defined objects as a key from HashMap. You can achieve this by implementing equals and hashcode methods at the user defined objects.

Java HashMap - HashMap Example, The important points about Java TreeMap class are: It stores key-value pairs similar to like HashMap. It allows only distinct keys. Duplicate keys are not possible. It cannot have null key but can have multiple null values. It stores the keys in sorted order (natural order) or by a Comparator provided at map creation time.

he was claiming that the HashMap was storing duplicate keys, not that he wanted to create a HashMap-like thing which will allow multiplevalues associated with a single key.You did not misread. I quote, "I'm using a HashMap".Yes, but he also says that he's looking for an alternative since he can't use a HashMap any longer.

  • Can you post a minimal reproducible example?
  • I disagree. I just tried exactly the provided code and this prints out what the op said.
  • @Schottky OPs code is not complete, how could you execute it as-it-is? Block and the JSON payload are missing. Please share the full code, then others can also reproduce and investigate.
  • @Zabuza that is the issue. Using this implementation, one key is a String and another key is a Long
  • You basically bypassed the generic-system. So with this, you can basically insert whatever you want in your map, not only Long. The map works the same still though, it will not allow duplicates. But by being able to insert whatever you want, you can easily insert stuff that looks similar but is actually different, like a string "0" vs a long 0 vs an integer 0 vs a short 0, ... all would be considered different.
  • Why the down-vote? I would like to improve the post.