{"record":{"id":"bb6d8e78b83a178f","repo":"google/gson","slug":"key-getclass-getname-is-not-comparable","errorCode":null,"errorMessage":"${key.getClass().getName()} 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/310ac341f2f92a454b229bf21f70d2d18b2b6db7/gson/src/main/java/com/google/gson/internal/LinkedTreeMap.java#L166-L202","documentation":"LinkedTreeMap in natural-ordering mode (no comparator) requires keys that implement Comparable. When the first key is inserted into an empty tree and the key is not instanceof Comparable, a ClassCastException is thrown (LinkedTreeMap.java:183) because there is no way to order it.","triggerScenarios":"Calling put on an empty LinkedTreeMap (natural order) whose key class does not implement Comparable, e.g. putting a POJO or array as a key.","commonSituations":"Using custom domain objects as map keys without implementing Comparable; using arrays or non-Comparable wrappers as keys; mixing key types across puts that are not mutually comparable.","solutions":["Implement Comparable on the key type, or pass a Comparator to the LinkedTreeMap constructor: new LinkedTreeMap<>(comparator, allowNullValues).","Use a HashMap keyed on a stable String/int field derived from the object instead of the object itself.","If keys are heterogeneous, define a Comparator that imposes a total order over all expected key types."],"exampleFix":"// before\nclass Key { String id; } // not Comparable\nmap.put(new Key(), value); // throws on first insert\n// after (option A: Comparable)\nclass Key implements Comparable<Key> {\n  public int compareTo(Key o){ return id.compareTo(o.id); }\n}\n// after (option B: comparator)\nnew LinkedTreeMap<Key,V>(Comparator.comparing(k -> k.id), true);","handlingStrategy":"validation","validationCode":"if (key != null && !(key instanceof Comparable) && comparator == null) throw new ClassCastException(\"key must be Comparable\");","typeGuard":"static boolean keyTypeOK(Class<?> k, Comparator<?> cmp) { return cmp != null || Comparable.class.isAssignableFrom(k); }","tryCatchPattern":"try { map.put(k, v); } catch (ClassCastException e) { /* non-comparable key */ }","preventionTips":["Implement Comparable on any class you intend to use as a key.","Pass an explicit Comparator to the LinkedTreeMap constructor when keys are not Comparable.","Prefer scalar/String keys derived from objects over the objects themselves."],"tags":["gson","collections","comparable","linkedtreemap"],"backgroundTag":null,"analyzedSha":"310ac341f2f92a454b229bf21f70d2d18b2b6db7","analyzedAt":"2026-08-10T02:58:47.455Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}