Eejayy
Eejayy

Reputation: 3

Gson throwing an error when using a hashmap

I'm trying to put 2 Integer[] values into a HashMap, however the gson library I've got in my maven dependencies is getting involved, and I can't wrap my head around why...

In this code below, "x" and "z" are both ints that come from a method from an API I'm using, that definitely return Integers, and are passed through parameters in a method and Claims.connectionMap is public and static in the main class.

Integer[] set = {x, z};
Claims.connectionMap.put(set, set); // LINE 110

And this is the connectionMap:

public static Map<Integer[], Integer[]> connectionMap = new HashMap<>();

This hashmap is exported and imported at the each start and stop of the server, but other than that, I can't fully understand why gson would be doing anything with this code, a forum post I read somewhere else aluded to it potentially being a build time error, but it imports into the code just fine (as far as I can tell): with this being the code to import

Map<Integer[], Integer[]> map;
// a few lines later
map = gson.fromJson(new String(array), Map.class);

But tragically, this error occurs on line 110 of the first code sample

31.01 10:19:23 [Server] INFO Caused by: java.lang.ClassCastException: [Ljava.lang.Integer; is not Comparable
31.01 10:19:23 [Server] INFO at com.google.gson.internal.LinkedTreeMap.find(LinkedTreeMap.java:164) ~[patched_1.16.4.jar:git-Paper-416]
31.01 10:19:23 [Server] INFO at com.google.gson.internal.LinkedTreeMap.put(LinkedTreeMap.java:94) ~[patched_1.16.4.jar:git-Paper-416]
31.01 10:19:23 [Server] INFO at com.eejay.towny.Towny.addConnection(Towny.java:110)

Any help would be greatly appreciated, thank you very much :)

Upvotes: 0

Views: 298

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

Gson is deserializing Map<Integer[], Integer[]> map using it's own LinkedTreeMap implementation which requires keys to implement Comparable interface.

Integer[] is an array so it doesn't implement a Comparable interface and can't be used as a key. I'm not sure why are you using arrays as keys as JSON normally uses String keys.

Upvotes: 2

Related Questions