1.equals()的所属以及内部原理(即Object中equals方法的实现原理)
说起equals方法,我们都知道是超类Object中的一个基本方法,用于检测一个对象是否与另外一个对象相等。而在Object类中这个方法实际上是判断两个对象是否具有相同的引用,如果有,它们就一定相等。其源码如下:
public boolean equals(Object obj) { return (this == obj); }
package com.company;
import java.util.HashMap;
class Student {
String name;
int age;
//true表示男,false表示女
boolean sex;
public Student(String ds, int i, boolean b) {
name = ds;
age = i;
sex = b;
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + (name == null ?0: name.hashCode());
result = 37 * result + age;
result = 37 * result + (sex ? 0 : 1);
return result;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Student &&
this.name.equals(((Student) obj).name) &&
this.age == ((Student) obj).age &&
this.sex == ((Student) obj).sex;
}
}
public class HashTest {
public static void main(String[] args) {
HashMap<Student, Integer> map = new HashMap<>();
map.put(new Student("ds", 1, true), -1);
map.put(new Student("ds", 1, true), -1);
map.put(new Student(null, 1, true), -1);
map.put(new Student("ds", 1, true), -1);
System.out.println(map.size());
}
}