Java “cannot cast to Comparable” when using TreeMap [duplicate]

给你一囗甜甜゛ 提交于 2019-11-29 10:05:50

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.

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.

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)

Your class has not implemented Comparable interface.

You have method compareTo(); so just add implements Comparable to your class MyVertex .

- First you should make class MyVertex implement Comparable.

Eg:

public class MyVertex implements Comparable {

  @Override
  public int compareTo(MyVertex o) {


  }
 }

- But if you want to compare on the basis of more than one attribute of the object, then its better to use java.util.Comparator<T> interface.

new TreeMap<MyVertex, Double>(new Comparator<MyVertex>()
        {
            public int compare(MyVertex o1, MyVertex o2)
            {

            } 
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!