如何使用compareTo()对对象列表进行排序,这在接口中默认实现?

问题描述 投票:-1回答:1

我无法在线找到问题的解决方案。如果您与类似问题共享链接,我将非常高兴。

我创建了扩展接口Shape的接口Comparable。我想将“ compareTo”方法作为默认方法放置在Shape界面中。类Circle实现了Shape,我想创建Circle的列表并对其进行排序。我的实现:

interface Comparable<T>{
  int compareTo (T other);
}

interface Shape extends Comparable<Shape>{ 

  abstract double getArea();
  abstract String toString();

  default int compareTo(Shape other){
    if(this.getArea() > other.getArea()) 
      return 1;
    if(this.getArea() < other.getArea()) 
      return -1;
    return 0;              
  }; 
}

class Circle implements Shape{
    double radius;
    Circle(double radius) {
        this.radius = radius;
    }
    public String toString() {
        return ""+radius+"";
    }
    public  double getArea(){
        return Math.PI * Math.pow(radius,2);
    }
}

然后我创建一个对象:Shape circle_1 = new Circle(2.4)当我直接调用该方法时,它确实起作用:circle_1.compareTo(circle_2)但是,当我尝试创建集合SortedSet<Shape> newtree = new TreeSet<Shape>()时,它遇到了一个错误:

Exception in thread "main" java.lang.ClassCastException: Circle cannot be cast to java.lang.Comparable
        at java.util.TreeMap.compare(Unknown Source)
        at java.util.TreeMap.put(Unknown Source)
        at java.util.TreeSet.add(Unknown Source)
        at App.main(App.java:68)

我在线发现,如果类Circle不会扩展Comparable接口,则可能会发生此错误,但是我想在我的代码中应该不会有问题,因为类Circle扩展了实现ShapeComparable ]。

我如何使用Collections根据compareTo方法对圈子列表进行排序?或如何创建无错误的SortedSet?

java sorting collections default compareto
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.