简体   繁体   中英

Java Hashcode and Equals for Java 8 functional interface objects

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM