1

I have my own class of which is an object with a set of other objects inside of it. i.e.

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;
}        
}

where the CurvePoint class implments Comparable and also overrides the equals method like so:

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;
    }

}

My question is when I have a 2 collections of Curve, how do I compare these to check if they equal? When I use the .equals it always just returns false, is there a way to do it without looping through both collections?

Twinhelix
  • 165
  • 2
  • 14
  • 1
    Nope. equals() implementations of standard collections always compare all children. Everything else would be awful – Sean Patrick Floyd Sep 12 '11 at 15:47
  • Possible duplicate of [Simple way to find if two different lists contain exactly the same elements?](https://stackoverflow.com/questions/1075656/simple-way-to-find-if-two-different-lists-contain-exactly-the-same-elements) – A Jar of Clay Jul 01 '19 at 10:23

2 Answers2

0

If you are comparing collections, then the collection needs to have a comparable interface which does the right thing for the collection.

Basically it is possible, but if the current collection doesn't implement comparison the way you like it, you'll need to subclass that collection and override the methods compareTo(...) and equals(...).

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
  • Basically I have overriden the compareTo() method in my curvePoint because I wanted them to be sorted according to date in my sorted set in my Curves. and I think what .equals on collections does is it loops through and calls .compareTo where as I want it to use the .equals. Is there a way to do this? – Twinhelix Sep 12 '11 at 15:52
0

Since you didn't show the whole code of CurvePoint just a check: getBid().getRate() and alike do return Primitives, not Wrapper objects, right? Because you compare them with == instead of equals().

ivy
  • 5,539
  • 1
  • 34
  • 48