Last active
August 29, 2015 13:58
-
-
Save mperry/9955705 to your computer and use it in GitHub Desktop.
Exploring equals and hash code for Java 8 Lamdas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.mperry; | |
import org.junit.Test; | |
import java.util.function.Function; | |
import static org.junit.Assert.assertTrue; | |
/** | |
* Created by MarkPerry on 3/04/2014. | |
*/ | |
public class IdTest { | |
@Test | |
public void simpleFuncId() { | |
info(func1(), func1(), true); | |
} | |
@Test | |
public void subFuncId() { | |
info(subFunction().apply(null), subFunction().apply(null), true); | |
} | |
@Test | |
public void equivalentFuncs() { | |
info(func1(), func2(), false); | |
} | |
void info(Function<Integer, String> f1, Function<Integer, String> f2, boolean expected) { | |
boolean eq = f1.equals(f2); | |
int f1h = f1.hashCode(); | |
int f2h = f2.hashCode(); | |
boolean he = f1h == f2h; | |
System.out.printf("f1=%s,f2=%s,f1h=%d,f2h=%d,eq=%b,he=%b\n", f1, f2, f1h, f2h, eq, he); | |
assertTrue((f1 == f2) == expected); | |
} | |
Function<Integer, String> func1() { | |
return (i -> i.toString()); | |
} | |
Function<Integer, String> func2() { | |
return (i -> i.toString()); | |
} | |
Function<Void, Function<Integer, String>> subFunction() { | |
return (v -> (i -> i.toString())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment