code_fish
code_fish

Reputation: 3434

java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.HashSet

I have following piece of code :

JsonObject json = (JsonObject) attVal;
HashSet<Map.Entry<String,JsonElement>> map = (HashSet<Map.Entry<String, JsonElement>>) json.entrySet();

I am getting below exception at line 2:

java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.HashSet

My json input is: {"key":"4e32cd954f31320078c5fd218110c7ca","number":"","unique_key":"001"}

What is the reason and how to solve this?

Upvotes: 0

Views: 1635

Answers (1)

m.antkowicz
m.antkowicz

Reputation: 13571

HashMap$EntrySet has nothing common with HashSet and because of this casting fails

You should rather iterate over json's entry set and add following values to your HashSet

HashSet<Map.Entry<String,JsonElement>> map = new HashSet<>();

for(Map.Entry<String,JsonElement> entry : json.entrySet()){
    if(entry != null) {
        map.put(entry.getKey(), jsonObject.get(entry.getKey()));
    }
}

Upvotes: 1

Related Questions