Search code examples
javadictionarytreemap

Error when putting <Object, Object> into TreeMap


I have the following two classes which define objects I would like to put into a TreeMap:

class GeneKey {

    String PN;
    int PW;

    // Generator makes unique TreeMap key.
    GeneKey(String a, int b){
        this.PN = a;
        this.PW = b;
    }
}   

Then a second object:

class GeneValue {

    String info;
    String date;

    // Generator makes TreeMap value
    GeneValue(String a, String b){
        this.info = a;
        this.date = b;
    }
}   

I would like to then make a TreeMap:

import java.util.TreeMap;

// In main ...
TreeMap<GeneKey, GeneValue> samples = new TreeMap<GeneKey, GeneValue>();  

String a = "test";
int b = 100;

String c = "test again";
String d = "test yet again";

// Try to put these objects into the tree map.
samples.put(new GeneKey(a, b) ,new GeneValue(c,d))

But I get the following error:

Exception in thread "main" java.lang.ClassCastException: GeneKey cannot be cast to java.lang.Comparable

I would like to know why I am not able to establish a TreeMap with key:value of GeneKey:GeneValue even though I specified those objects when initializing my TreeMap. How to I initialize the map in order to .put() these two objects.

Thank you


Solution

  • TreeMap is an ordered container: when you request its keys or its entries, you get them in a certain order.

    The order depends on the key that you supply. In order for the container to order the keys, each key needs to implement Comparable interface:

    class GeneKey implements Comparable<GeneKey> {
    
        String PN;
        int PW;
    
        // Generator makes unique TreeMap key.
        GeneKey(String a, int b){
            this.PN = a;
            this.PW = b;
        }
        public int compareTo(GenKey other) {
            int res = PN.compareTo(other.PN);
            return (res != 0) ? res : Integer.compare(PW, other.PW);
        }
    }
    

    This is not a requirement for hash-based container, because everything inherits from Object, which supplies hashCode and equals.