Skip to content

Commit 53a055a

Browse files
committed
Add Ord.hashEqualsOrd that checks hashCode and equals.
1 parent 7d366ef commit 53a055a

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

core/src/main/java/fj/Ord.java

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -639,9 +639,12 @@ public Ordering f(final A a2) {
639639
}
640640

641641
/**
642-
* An order instance that uses {@link Object#hashCode()} for computing the order.
642+
* An order instance that uses {@link Object#hashCode()} for computing the order and equality,
643+
* thus objects returning the same hashCode are considered to be equals (check {@link #hashEqualsOrd()}
644+
* for an additional check on {@link Object#equals(Object)}).
643645
*
644646
* @return An order instance that is based on {@link Object#hashCode()}.
647+
* @see #hashEqualsOrd()
645648
*/
646649
public static <A> Ord<A> hashOrd() {
647650
return Ord.<A> ord(new F<A, F<A, Ordering>>() {
@@ -658,4 +661,26 @@ public Ordering f(final A a2) {
658661
});
659662
}
660663

664+
/**
665+
* An order instance that uses {@link Object#hashCode()} and {@link Object#equals()} for computing
666+
* the order and equality. First the hashCode is compared, if this is equal, objects are compared
667+
* using {@link Object#equals()}.
668+
*
669+
* @return An order instance that is based on {@link Object#hashCode()} and {@link Object#equals()}.
670+
*/
671+
public static <A> Ord<A> hashEqualsOrd() {
672+
return Ord.<A> ord(new F<A, F<A, Ordering>>() {
673+
@Override
674+
public F<A, Ordering> f(final A a) {
675+
return new F<A, Ordering>() {
676+
@Override
677+
public Ordering f(final A a2) {
678+
final int x = a.hashCode() - a2.hashCode();
679+
return x < 0 ? Ordering.LT : x == 0 && a.equals(a2) ? Ordering.EQ : Ordering.GT;
680+
}
681+
};
682+
}
683+
});
684+
}
685+
661686
}

0 commit comments

Comments
 (0)