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);
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Object.equals()
接受一个参数。这是正确的。但是在这里,您引入了一个函数,该函数既接受要比较的对象(this
),又接受预期的参数equals
(另一个对象)。
因此,您需要BiPredicate<Person,Person>
允许传递两个信息。
我认为您混淆的根源是方法参考:
checkHere(Person::equals);
Run Code Online (Sandbox Code Playgroud)
将其转换为lambda,它应该使事情更清晰:
(o1, o2) -> o1.equals(o2)
实际上,您确实需要向函数传递两个参数以允许其替换o1
,o2
然后执行此操作:
return pc.test(p1, p2);
Run Code Online (Sandbox Code Playgroud)