Search code examples
javaobjecthashmaptreemapcomparable

How to solve problem with Java TreeMap when you use object as key?


package RecyclingJava.recycling;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

public class knot{

    //ArrayList<knot> connect= new ArrayList<>(); //ArrayList
    //Map<knot, Boolean> connect= new HashMap<knot, Boolean>(); //HashMap
    Map<knot, Boolean> connect= new TreeMap<>(); //TreeMap
    @Deprecated
    @Override
    
    
    protected void finalize() throws Throwable 
    {
        System.out.println("Finalize object");
        super.finalize();
    }

    public void addconnection(knot knot)   {
        //this.connect.add(knot);  // ArrayList
        this.connect.put(knot,true); //HashMap
        //this.connect.put(1, true);
    }

    public static void main(String[] args) {

        
        //Scanner s = new Scanner(System.in);
        for (int i = 0; i <= 1000000; i++)
        {
            //new Wezel() ;
            knot w1 = new knot();
            knot w2 = new knot();
            //System.out.println(w1);
            w1.addconnection(w2);
            w2.addconnection(w1);
        }
        
        //s.nextLine();
        //s.close();
        

    }
}

I have to use TreeMap to make connection between two objects, but i got this error when using TreeMap class RecyclingJava.recycling.knot cannot be cast to class java.lang.Comparable

I tried using compactor by it didn't work


Solution

  • The TreeMap is sorted by the ordering of its keys. If you should not need a sorted map, you can replace TreeMap with an other class that implements Map (for example HashMap). If you really need a sorted map you have to define the ordering of your key objects. You can do this in two ways:

    A) Specify a Comparator as paramter for the constructor

    Comparator<knot> comparator = ...
    Map<knot, Boolean> connect = new TreeMap<>(comparator);
    

    B) Implement Comparable

    public class knot implements Comparable<knot> {
    
      ...
    
      public int compareTo​(knot other) {
       
        // TODO: return a negative integer, zero, or a positive integer as this 
        // object is less than, equal to, or greater than the other object.
        ...
      }
    }
    

    When you do not specify a Comparator the TreeMap expects that you've chosen variant B and tries to cast your key object to Comparable. Since you neither specify a Comparator nor implement Comparable, the TreeMap complains with the described error.

    For more details, please see the following JavaDocs:

    TreeMap Comparator Comparable Map