我有两个对象-RightTriangle和Rectangle。这两个类都实现了“ Shape”接口,该接口具有2种抽象的面积和周长方法。在RightTriangle类中,我实现可比的,并且compareTo返回area:perimeter ratio。我在Rectangle类中也做同样的事情。在演示中,我想使用Collections.sort()对RightTriangle对象和Rectangle对象的数组进行排序。

形状接口代码:

public interface Shape
{
    public double getArea();
    public double getPerimeter();
}


RightTriangle代码:

public class RightTriangle implements Shape, Comparable<Shape>
{
    private int leg1, leg2;
    public RightTriangle(int lg1, int lg2)
    {
        leg1 = lg1;
        leg2 = lg2;
    }


    public double getArea()
    {
        return (.5*leg1*leg2);
    }

    public double getPerimeter()
    {
        return (leg1+leg2 + getHypotenuse());
    }


    private double getHypotenuse()
    {
        return (Math.sqrt(Math.pow(leg1,2)+Math.pow(leg2,2)));
    }

    public int compareTo(Shape obj)
    {
        return (int)(getArea()/getPerimeter());
    }

}


矩形码:

public class Rectangle implements Shape, Comparable<Shape>
{
    private int length, width;

    public Rectangle(int l, int w)
    {
        length = l;
        width = w;
    }

    public double getArea()
    {
        return (width*length);
    }

    public double getPerimeter()
    {
        return (2*width + 2*length);
    }

    public int compareTo(Shape obj)
    {
        return (int)(getArea()/getPerimeter());
    }

}


演示:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
public class Demo
{
    public static void main (String[] args)
    {
        RightTriangle right = new RightTriangle(12,14);
        Rectangle rect = new Rectangle(7,10);
        ArrayList<Shape> al = new ArrayList<Shape>();
        al.add(right);
        al.add(rect);
        Collections.sort(al);
        for (int i = 0; i < al.size(); i++)
        {
            System.out.println (al.get(i));
        }
    }

}


我收到一个错误-“错误:找不到适合sort(ArrayList)的方法。如何解决此问题?

谢谢。

最佳答案

1.您需要将Comparable接口扩展到Shape接口,而不是像下面这样训练和矩形类

public interface Shape extends Comparable<Shape>
{
 public double getArea();
 public double getPerimeter();
 public int compareTo(Shape obj);
}


2. RightTriangle和Rectangle类将仅将Shape接口实现为

public class RightTriangle implements Shape
public class Rectangle implements Shape


** 3。通过右键单击代码..select源->生成toString(),在RightTriangle和Rectangle类中都实现toString方法。

@Override
public String toString() {
    return "RightTriangle [leg1=" + leg1 + ", leg2=" + leg2 + "]";
}

@Override
    public String toString() {
        return "Rectangle [length=" + length + ", width=" + width + "]";
    }


**更正代码后查看我得到的结果
java - Java使用Comparable,Collections.sort()对自定义对象进行排序-LMLPHP

09-26 00:19