【问题标题】:Java Collection of own Objects and .equals自己的对象和 .equals 的 Java 集合
【发布时间】:2011-09-13 00:13:50
【问题描述】:

我有自己的类,它是一个对象,其中包含一组其他对象。 即

public class Curve{


@Override
public Collection<CurvePoint> getCurvePoints() {
return curvePoints;
}

@Override
public boolean equals(Object other) {
    if (other instanceof Curve) {
        Curve otherCurve = (Curve) other;
        return getCurvePoints().equals(otherCurve.getCurvePoints());
    }
    return false;
}        
}

CurvePoint 类实现 Comparable 并且还覆盖了 equals 方法,如下所示:

public class CurvePoint implements ICurvePoint, Comparable<CurvePoint> {

@Override
    public int compareTo(CurvePointother) {

        return getSnapDate().compareTo(other.getSnapDate());

    }
@Override
    public boolean equals(Object other) {
        if (other instanceof CurvePoint) {
            CurvePointotherPoint = (CurvePoint) other;

            return (getId().equals(otherPoint.getId())
                    && getBid().getRate() == otherPoint.getBid().getRate()
                    && getOffer().getRate() == otherPoint.getOffer().getRate() && getMid()
                    .getRate() == otherPoint.getMid().getRate());
        }
        return false;
    }

}

我的问题是,当我有 2 个 Curve 集合时,如何比较它们以检查它们是否相等?当我使用 .equals 时,它总是只返回 false,有没有办法在不遍历两个集合的情况下做到这一点?

【问题讨论】:

标签: java collections equals


【解决方案1】:

如果您要比较集合,那么集合需要有一个可比较的接口,该接口可以为集合做正确的事情。

基本上这是可能的,但如果当前集合没有按照您喜欢的方式实现比较,您需要将该集合子类化并覆盖方法compareTo(...)equals(...)

【讨论】:

  • 基本上我已经覆盖了我的曲线点中的 compareTo() 方法,因为我希望它们根据我在曲线中的排序集中的日期进行排序。我认为集合上的.equals 所做的是循环并调用.compareTo,因为我希望它使用.equals。有没有办法做到这一点?
【解决方案2】:

由于您没有显示 CurvePoint 的整个代码,因此只进行了检查:getBid().getRate() 和类似的方法确实返回 Primitives,而不是 Wrapper 对象,对吧?因为您将它们与 == 而不是 equals() 进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 2011-07-09
    • 2012-05-16
    • 2019-07-21
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多