Java "cannot cast to Comparable" when using TreeMap

30,147

Solution 1

How do I get MyVertex types to be casted to Comparables?

Implement Comparable interface.

public class MyVertex implements Comparable<MyVertex> {

  @Override
  public int compareTo(Object o) {
   // comparison logic goes here

  }
 }

or alternately, you can pass a comparator to the constructor of TreeMap.

 new TreeMap<MyVertex, Double>(new Comparator<MyVertex>()
        {
            public int compare(MyVertex o1, MyVertex o2)
            {
                //comparison logic goes here
            } 
    });

Why is this necessary?

Because you are storing in tree map which is a sorted map (sorted by keys). Map Keys need to be comparable to ensure a sort order in the map.

Solution 2

The behaviour is compliant with the javadoc of TreeMap:

Throws ClassCastException if the specified key cannot be compared with the keys currently in the map

There are essentially two ways to make it work:

  • either make MyVertex implement Comparable<MyVertex>
  • or pass a Comparator<MyVertex> to the constructor of your TreeMap

Note that before Java 7, the exception would only be thrown when adding a second item to the map whereas with Java 7 the exception is thrown when adding one item to the map.

Solution 3

MyVertex class should implement Comparable as tree map uses the compareTo method to order the map based on keys.

public class MyVertex implements Comparable<MyVertex> {

  @Override
  public int compareTo(MyVertex o) {
   // do the comparison logic

  }
 }

Other option is to pass a Comparator Object to TreeMap http://docs.oracle.com/javase/1.5.0/docs/api/java/util/TreeMap.html#TreeMap(java.util.Comparator)

Share:
30,147
CodeKingPlusPlus
Author by

CodeKingPlusPlus

Updated on July 16, 2022

Comments

  • CodeKingPlusPlus
    CodeKingPlusPlus almost 2 years

    Possible Duplicate:
    Java: SortedMap, TreeMap, Comparable? How to use?

    I am using the Java JungI graph package and Netbeans 7. I am getting the following error from Java:

     Exception in thread "main" java.lang.ClassCastException: graphvisualization.MyVertex cannot be cast to java.lang.Comparable
        at java.util.TreeMap.put(TreeMap.java:542)
    

    Here is the code associated with the error:

    SortedMap<MyVertex, Double> vMap = new TreeMap<MyVertex, Double>();
           double curRank = 0;
           for(MyVertex v: g.getVertices())                 //g is a SparseGraph<MyVertex, MyEdge>
           {
               curRank = vertexRank.getVertexScore(v);
               vMap.put(v, curRank);                        //**Here is my Error**
           }
    

    Class MyVertex is a class I made for graphs. The following is the code for MyVertex

    public class MyVertex 
    {
        int vID;                    //id for this vertex
        double centrality;          //centrality measure for this vertex
        int degree;                 //the degree of this vertex
    
        public MyVertex(int id)
        {
            this.vID = id;
            this.centrality=0;
            this.degree=0;
        }
    
        public double getCentrality()
        {
            return this.centrality;
        }
    
        public void setCentrality(double centrality)
        {
            this.centrality = centrality;
        }
    
        public int getDegree()
        {
            return this.degree;
        }
    
        public void setDegree(int deg)
        {
            this.degree = deg;
        }
    
        public void incrementDegree()
        {
            this.degree++;
        }
    
        public void decrementDegree()
        {
            this.degree--;
        }
    
        @Override
        public String toString()
        {
            return "v"+vID;
        }
    
        int compareTo(MyVertex v) 
        {
            return (this.degree < v.degree) ? 1 : 0;          //this will do descendingly
        }
    }
    
    1. How do I get MyVertex types to be casted to Comparables?
    2. Why is this necessary? (I do not immediately see the reason)
  • Subin Sebastian
    Subin Sebastian over 11 years
    last note is interesting