Java使用Comparable,Collections.sort()对自定义对象进行排序

时间:2017-11-30 00:52:23

标签: java sorting object collections comparable

我有两个对象 - RightTriangle和Rectangle。这两个类都实现了#34; Shape"界面有2个面积和周长的抽象方法。在RightTriangle类中,我实现了可比较的和我的compareTo返回区域:周长比。我在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));
        }
    }

}

我收到错误 - &#34;错误:没有为sort(ArrayList)找到合适的方法。我该如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:0)

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 source-> generate toString()

在RightTriangle和Rectangle类中实现toString方法
@Override
public String toString() {
    return "RightTriangle [leg1=" + leg1 + ", leg2=" + leg2 + "]";
}

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

**更正代码后,看到我得到的结果 See the result i got after correcting your code

相关问题