Java Hashcode and Equals for Java 8 Functional Interface Objects

I have a code that looks like this:

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 would check that some Function, Supplier, BiFunctionor something else that may be MyObj, will be equal to the other, if the result of the call Function/ Supplieretc returns the same value with the same input.

So, in this case, Java compares the values ​​of two lists with equals, for example, functionList1.get(0).apply(standardInstanceOfMyObj)equal functionList2.get(0).apply(standardInstanceOfMyObj), etc.

My question is, how can I override equalsand hashcodeto a certain type, for example Function<MyObj, String>, to do the work above?

+4
source share
1 answer

. , Function. () , , Java , ( , equals() ). , equals()/hashCode() (, , ), .

+2

Source: https://habr.com/ru/post/1688091/


All Articles