TreeSet - >在Java中覆盖compareTo

时间:2014-02-13 17:51:10

标签: java comparable treeset

首先,我有这个界面:

public interface GeometricFigureInterface extends Comparable {

double getArea();

TreeSet<?> getByText(String text);

@Override
public int compareTo(Object o);

}

然后是一个矩形

public class Dreptunghi implements GeometricFigureInterface {

private double x1;
private double y1;
private double x2;
private double y2;

public Dreptunghi() {
    super();
}

public Dreptunghi(double x1, double y1, double x2, double y2) {
    super();
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
}

@Override
public double getArea() {
    return Math.sqrt(Math.pow(x1 - y2, 2) + Math.pow(x2 - y2, 2));
}

我有一种从文本中读取coordonates的方法

@Override
public TreeSet<Dreptunghi> getByText(String text) {
    String file ="D:/FiguriGeometrice.txt"; 
    BufferedReader br = null;
    TreeSet<Dreptunghi> setDreptunghiuri = new TreeSet<Dreptunghi>();
    Dreptunghi d = new Dreptunghi();
    try {

        String line = "";
        FileReader fr = new FileReader(file);
        br = new BufferedReader(fr);

        while ((line = br.readLine()) != null) {

            String[] s = line.split(" ");
            if (s[0].equals("D")) {
                d.setX1(Double.parseDouble(s[1]));
                d.setY1(Double.parseDouble(s[2]));
                d.setX2(Double.parseDouble(s[3]));
                d.setY2(Double.parseDouble(s[4]));

//当我添加这个时,这是我的问题 调用compareToMethod,但对象是相同的,我最终只有一个对象,无论值是什么

                setDreptunghiuri.add(d);

            }

        }
    } catch (Exception e) {
        ....

    }
    return setDreptunghiuri;
}

@Override
public int compareTo(Object o) {
    Dreptunghi d = (Dreptunghi)o;
    if(this.getX1() == d.getX1())
        return 0;
    return 1;
}

1 个答案:

答案 0 :(得分:0)

在循环内定义类或仅在条件

内初始化它
if (s[0].equals("D")) {
            Dreptunghi d = new Dreptunghi();
            d.setX1(Double.parseDouble(s[1]));
            d.setY1(Double.parseDouble(s[2]));
            d.setX2(Double.parseDouble(s[3]));
            d.setY2(Double.parseDouble(s[4]));

            setDreptunghiuri.add(d);

        }

 if (s[0].equals("D")) {
                d = new Dreptunghi();
                d.setX1(Double.parseDouble(s[1]));
                d.setY1(Double.parseDouble(s[2]));
                d.setX2(Double.parseDouble(s[3]));
                d.setY2(Double.parseDouble(s[4]));

                setDreptunghiuri.add(d);

            }