{"id":"89cab2c91d5b33f6","repo":"google/gson","slug":"classname-is-not-comparable","errorCode":null,"errorMessage":"{className} is not Comparable","messagePattern":"(.+?) is not Comparable","errorType":"exception","errorClass":"ClassCastException","httpStatus":null,"severity":"error","filePath":"gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java","lineNumber":184,"sourceCode":"          break;\n        }\n\n        nearest = child;\n      }\n    }\n\n    // The key doesn't exist in this tree.\n    if (!create) {\n      return null;\n    }\n\n    // Create the node and add it to the tree or the table.\n    Node<K, V> header = this.header;\n    Node<K, V> created;\n    if (nearest == null) {\n      // Check that the value is comparable if we didn't do any comparisons.\n      if (comparator == null && !(key instanceof Comparable)) {\n        throw new ClassCastException(key.getClass().getName() + \" is not Comparable\");\n      }\n      created = new Node<>(allowNullValues, nearest, key, header, header.prev);\n      root = created;\n    } else {\n      created = new Node<>(allowNullValues, nearest, key, header, header.prev);\n      if (comparison < 0) { // nearest.key is higher\n        nearest.left = created;\n      } else { // comparison > 0, nearest.key is lower\n        nearest.right = created;\n      }\n      rebalance(nearest, true);\n    }\n    size++;\n    modCount++;\n\n    return created;\n  }\n","sourceCodeStart":166,"sourceCodeEnd":202,"githubUrl":"https://github.com/google/gson/blob/8b8628c65699bc4421696183c62ae0c1b9b281dc/gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java#L166-L202","documentation":"Thrown by LinkedTreeMap.find() as a ClassCastException ('<className> is not Comparable') when the map is using natural ordering (no comparator supplied) and the first key inserted does not implement Comparable. LinkedTreeMap orders keys via compareTo; without a Comparator and without Comparable keys it has no way to position nodes, so it rejects the key rather than producing undefined ordering.","triggerScenarios":"Calling put(key, value) where key's class does not implement Comparable, on a LinkedTreeMap created with the no-arg or LinkedTreeMap(boolean) constructors (natural order). The check only fires on the first insertion because that is the first time a comparison would be attempted.","commonSituations":"Using a POJO/domain class as a map key without implementing Comparable; Gson deserializing into a Map<MyPojo, V> where MyPojo is not Comparable; mixing key types inadvertently.","solutions":["Make the key class implement Comparable and implement compareTo consistently with equals.","Supply a Comparator when creating the map: new LinkedTreeMap<>(myComparator, true).","Use a HashMap/LinkedHashMap if you only need hash-based keys and do not require ordering."],"exampleFix":"// before\nclass Key { String id; } // not Comparable\nLinkedTreeMap<Key, Integer> m = new LinkedTreeMap<>();\nm.put(new Key(), 1); // throws\n\n// after: implement Comparable\n class Key implements Comparable<Key> {\n   public int compareTo(Key o) { return id.compareTo(o.id); }\n }","handlingStrategy":"type-guard","validationCode":"static boolean isComparableKey(Object key) {\n  return key instanceof Comparable;\n}\n// usage: if (!isComparableKey(k)) throw new IllegalArgumentException(\"key must be Comparable\");","typeGuard":"static <K> boolean keyTypeIsComparable(Class<K> type) {\n  return Comparable.class.isAssignableFrom(type);\n}","tryCatchPattern":"try {\n  map.put(key, value);\n} catch (ClassCastException e) {\n  if (e.getMessage().contains(\"not Comparable\")) {\n    // rebuild the map with an explicit Comparator and retry\n    map = new LinkedTreeMap<>(myComparator, map.allowNullValues);\n  } else throw e;\n}","preventionTips":["Ensure key types implement Comparable, or supply a Comparator.","Use HashMap when ordering is not required.","Validate key class implements Comparable at construction time for natural-order maps."],"tags":["gson","collection","linkedtreemap","comparable","classcastexception"],"analyzedSha":"8b8628c65699bc4421696183c62ae0c1b9b281dc","analyzedAt":"2026-08-04T19:12:22.202Z","schemaVersion":2}