I have this method:
private SortedMap<String, SpaceObjectImpl> catalog = new TreeMap<String, SpaceObjectImpl>();
public Collection<SpaceObject> getSpaceObjects(){
SortedSet<SpaceObject> temp = new TreeSet<SpaceObject>(catalog.values());
return temp;
}
while compareTo is defined here:
public int compareTo(SpaceObjectImpl s){
....
}
class SpaceObjectImpl implements SpaceObject
When i run program, ClassCastException is thrown. Any idea why?
error:
SpaceObjectImpl cannot be cast to java.lang.Comparable(in TreeMap)
Your
SpaceObjectImplmust implementComparableinterface.The following is an example by mkyong that illustrates this concept:
Here, the
Fruitclass has implementedComparableinterface with type asFruitand has alsooverridencompareTomethod.