s-day01-Object类的equals方法
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package com.inmind.object01;
|
||||
/*
|
||||
Object类的equals方法:
|
||||
boolean equals(Object obj) 指示一些其他对象是否等于本对象(判断对象内容)
|
||||
|
||||
== :
|
||||
基本数据类型:比较2个数据值是否相同
|
||||
引用数据类型:比较的是地址是否相同
|
||||
|
||||
在实际开发中,地址值对我们没有太大的作用,比较关心数据内容,经常将内容相同的2个对象,看作是同一个,要使用Object的equals方法
|
||||
|
||||
Object父类的源码:
|
||||
public boolean equals(Object obj) {
|
||||
return (this == obj);
|
||||
}
|
||||
如果父类的内容比较功能,不符合子类(Student)的需求,那就重写equals方法
|
||||
|
||||
|
||||
*/
|
||||
public class Demo03 {
|
||||
public static void main(String[] args) {
|
||||
String s1 = "123";
|
||||
String s2 = "123";
|
||||
System.out.println(s1 == s2);// true
|
||||
|
||||
//创建2个学生对象(内容相同的2个对象,看作是同一个)
|
||||
Student stu1 = new Student("张三", 18);
|
||||
Student stu2 = new Student("张三", 18);
|
||||
System.out.println(stu1 == stu2);//false
|
||||
System.out.println(stu1.equals(stu2));//true!
|
||||
}
|
||||
}
|
||||
@@ -19,4 +19,24 @@ public class Student extends Object{
|
||||
", age=" + age +
|
||||
'}';
|
||||
}
|
||||
|
||||
//重写equals方法,不要比较地址,比较内容
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;//地址相同,内容相同
|
||||
}
|
||||
//地址不同,判断类型
|
||||
if (obj instanceof Student) {
|
||||
//就比较学生的内容
|
||||
Student s = (Student) obj;
|
||||
if (this.name.equals(s.name) && this.age == s.age) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user