4 ms·
Equality in general is a surprisingly subtle subject. "When is one thing equal to some other thing?"[1] is a fun article about it. Java's equals method has two
by tikhonj 10y ago
Equality in general is a surprisingly subtle subject. "When is one thing equal to some other thing?"[1] is a fun article about it.
Java's equals method has two core problems in my eyes: it forces every type to define equality (when some types really shouldn't) and it lets you compare any two values, even if they don't have compatible types. My Java is rusty, but I think an Eq<T> interface comparable to Comparable<T> would be a reasonable design:
public interface Eq<T> {
public boolean equals(T o);
}
In particular, I don't mind the fact that there can be at most one equals per type: it's a sensible default 99% of the time. Most things that admit some sort of equality have an "obvious" default equality that makes sense; it's fine to make other comparison functions more explicit. Weird types with no obvious default equals method just shouldn't implement that interface. Worst case, you could just construct a wrapper that exposes a particular equals for that type.
- jayd16 10y agoWhat is an example of a type that should not have an equality?
- berdario 10y agoThe most obvious are lambdas (anything in this package, basically): https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html https://docs.oracle.com/javase/8/docs/api/java/util/function... Iterable/Iterator in general might also be problematic, since they might yield an infinite sequence of values (trying to equate them would loop indefinitely... obviously you can write a concrete class that is guaranteed to iterate a finite number of times, but this means that you should then implement an Equality interface only for them) Also, anything that is thus closely related to Streams, references to stuff in the outside world or things that aren't easily Serializable (and thus are probably not Value Objects), like File Handles/Sockets (you might compare them by reference, obviously) Also, Float and Doubles should arguably not implement an Equality interface. Rust for example does not have them implement Eq, but rather PartialEq due to NaN. Any Product (composite) or Sum type containing any such value might also not make sense to implement value equality PS: I think that Tikhon forgot to link the document he mentioned, this should be it: http://abel.math.harvard.edu/~mazur/preprints/when_is_one.pdf http://abel.math.harvard.edu/~mazur/preprints/when_is_one.pd...
- ygra 10y agoWhile anonymous functions should really only have reference equality, I still think the Java designers fucked up in extending this to method references. this::foo != this::foo, which is a bit painful for registering event listeners when you want to remove them later again. For those things you have to store the reference in a field.