I have some code which looks like the below:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
class MyObj {
private final Double aDouble;
public MyObj(Double aDouble) {
this.aDouble = aDouble;
}
}
class Main {
public static void main(String[] args) {
List<Function<MyObj, String>> functionList1 = new ArrayList<>();
List<Function<MyObj, String>> functionList2 = new ArrayList<>();
// ... Add same Function<MyObj, String>s to both lists
// I want to assert that functionList1.equals functionList2
}
}
I'd like to check that some Function
, Supplier
, BiFunction
or whatever it might be of MyObj
, would be equal to another if the result of calling the Function
/Supplier
etc returns the same value given the same input.
So in this case, Java would compare the values of the two lists using equals
like so functionList1.get(0).apply(standardInstanceOfMyObj)
equals functionList2.get(0).apply(standardInstanceOfMyObj)
etc.
My question is, how can I override equals
and hashcode
for a specific type like Function<MyObj, String>
to make the above work?
Answer. Yes, Comparator is a functional interface. The equals is an abstract method overriding one of the public methods of java. lang.
Three of the Object methods cannot have default methods for the reasons given above by Brian Goetz: equals(Object) , hashCode() , and toString() .
Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.
Object . Unfortunately, an interface can not enforce its implementation classes to override these methods, but that shouldn't stop it from declaring it to document the contract.
You can't. You can, however, override them for any class of yours that does actually implement Function
. Comparing functions (mathematically) is tricky business since the domain space might be infinite, so Java would have no way to know that two functions are the same (other than in the case of numerical identity, where equals()
will be true anyway). If you have some specific functions for which you can provide a more fine-grained equals()
/hashCode()
(for example, because they are based on some parsed expression language and you can compare the string representations), then you'll have to write those criteria in your own class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With