I was practicing my Java 8 skills. I came across a strange (for me) code. I have my bean class Person
with overridden equals
method. Then I tried to implement BiPredicate
with equals method. It ran successfully. Can anyone explains how's that possible..because in my opinion equals method takes 1 argument and BiPridicate's test
method takes two arguments. How is it satisfying this condition?
My code--
Method_Ref1
package method_referencing;
import java.util.function.BiPredicate;
import method_referencing.Person;
//1. static ....
//2. instance ...
//3. arbitary object
//4. constructor
public class Method_Ref1 {
public static void main(String[] args) {
System.out.println(checkHere(Person::equals));
}
static boolean checkHere(BiPredicate<Person,Person> pc) {
Person p1 = new Person(11,"Tom","Male","coder");
Person p2 = new Person(21,"Tom","male","coder");
return pc.test(p1, p2);
}
}
Person
package method_referencing;
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 5721690807993472050L;
int id;
String name;
String gender;
String note;
public Person() {
}
public Person(int id, String name, String gender, String note) {
this.id = id;
this.name = name;
this.gender = gender;
this.note = note;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
return "id=" + id + ", name=" + name + ", gender=" + gender + ", note=" + note + "";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((note == null) ? 0 : note.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Object.equals()
accepts a single parameter. It is right. But here your introduced a function that accepts both the object to compare (this
) and the parameter expected for equals
(the other object).
So you need a BiPredicate<Person,Person>
to allow to pass both information.
I think that the origin of your confusion is the method reference :
checkHere(Person::equals);
Convert it into a lambda, it should do things clearer : (o1, o2) -> o1.equals(o2)
You indeed need to pass two arguments to the function to allow it substitute o1
and o2
and you do that :
return pc.test(p1, p2);