“==”、equals和hashCode有什么区别?
“==”:
1如果比较的对象是基本数据类型,则比较的数值是否相等;
2.如果比较的是引用数据类型,则比较的是对象的地址值是否相等;
int a = 5;
int b = 5;
String s1 = new String("xyz");
String s2 = new String("xyz");
System.out.println(a == b); // true
System.out.println(s1== s2); // false
解释:a 和 b都是基本数据类型,直接比较值是否相等即可。
String s1 = new String(“xyz”);
变量s1存储在栈空间中,new String(“xyz”)存储在堆内存空间中,
xyz 存储在常量区中。此时变量s1指向的是 new出来对象的首地址,即
s1=0X0001,s2=0X0002
equals:
1、在没有重写equals方法的情况下,equals比较的是引用类型变量所指向的对象的地址。(相当于“==”的第二种情况)
2、重写equals方法的情况下,equals比较的是两个对象中的内容是否相同。
情况一演示:
public class Demo01 {
public static void main(String[] args) {
Student s1 = new Student("xiaohong");
Student s2 = new Student("xiaohong");
System.out.println(s1.equals(s2));//false
}
}
class Student{
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
}
情况二演示:
public class Demo01 {
public static void main(String[] args) {
Student s1 = new Student("xiaohong");
Student s2 = new Student("xiaohong");
System.out.println(s1.equals(s2));//true
}
}
class Student{
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
//重写了equals方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name);
}
}