我创建了一个对象列表,并在其中添加了Circle和Square等元素。我在sqaure和circle类中添加了一个方法,它检查对象的实例并比较该区域。
public class Circle extends Shape implements Comparable <Object>{
public int compareTo(Object otherObject) {
double difference=0.0;
int retValue= 3;
if(otherObject instanceof Circle){
Circle circle= (Circle)otherObject;
difference= this.area()- circle.area(); //calculate the difference of areas
}
if(otherObject instanceof Square){
Square square= (Square)otherObject; //Casting the object to Sqaure
difference= this.area()- square.area();//Calculate difference of Areaareas
}
if(difference == 0.0)retValue = 0; //return 0 if area is equal
if(difference < Shape.TOLERANCE)retValue = -1; //return -1 if area of the circle is less than the otherObject
if(difference > Shape.TOLERANCE)retValue = 1; //return 1 if area of the circle is more than the otherObject
return retValue;
}
}
我想要对其进行排序的课程如下: -
List<Object> objectList = new ArrayList<Object>();
当我正在尝试Collections.sort(objectList)
时,它给了我一个错误
no suitable method found for sort(List<Object>)
任何建议。我也宣布我的班级是
答案 0 :(得分:2)
苹果与橘子,或在您的情况下圈子与正方形。
您需要让它们共享一个共同的方面,这意味着您需要使用Shape2D
方法实现double getArea()
接口。
然后,您可以撰写Comparator<Shape2D>
并致电sort(myShapeList, myAreaComparator)
。
<强>更新强>
鉴于现在显示的额外代码,您已经拥有公共基类Shape
,它似乎有abstract double area()
方法,由Circle
和{{1}实现}。
然后,您将Square
更改为Shape
(而非Comparable<Shape>
),Object
方法(现在以compareTo()
为参数)可以调用Shape
没有任何演员。
答案 1 :(得分:0)
将Circle
与Object
进行比较是没有意义的。
如果您想按区域对圆圈和方块进行排序,
改为使用Comparator
。
它也有意义:
List<Shape>
而不是List<Object>
Comparator<Shape>
可以使用Shape.area
进行排序Double.compare
比较区域,而不是手动if-else 这样的事情:
public void demo() {
List<Shape> shapes = new ArrayList<>();
shapes.add(new Circle(2));
shapes.add(new Square(2));
shapes.add(new Square(1));
shapes.add(new Circle(1));
Collections.sort(shapes, new Comparator<Shape>() {
@Override
public int compare(Shape o1, Shape o2) {
return Double.compare(o1.area(), o2.area());
}
});
System.out.println(shapes);
}
Shape
,Circle
,Square
的实施可以像这样简单:
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return radius * radius * Math.PI;
}
@Override
public String toString() {
return "Circle(" + radius + ")";
}
}
class Square extends Shape {
private final double side;
Square(double side) {
this.side = side;
}
@Override
double area() {
return side * side;
}
@Override
public String toString() {
return "Square(" + side + ")";
}
}