一、关于object类中的equals方法
1、eqals方法的源代码:
public boolean equals (Object obj) {
return (this == obj) ;
}
以上这个方法是Object类的默认实现。
作用:equals方法来判断两个对象是否相等
2. 代码演示equals重写
public class Test {
public static void main(String[] args) {
//判断两个基本数据类型的数据是否相等直接使用"=="就行
int a=100;
int b=100;
//这个"=="是判断a中保存的100和b中保存的100是否相等
System.out.println(a==b);
//true (相等) false(不相等)
//判断两个java对象是否相等,我们能直接使用"=="吗?
// 创建一个日期对象是,2008年8月8日
MyTime t1=new MyTime(2008,8,8); //MyTime t1 =0x1234;//
// 创建了一个新的日期对象,但表示的日期也是,2008年8月8日
MyTime t2=new MyTime(2008,8,8); //MyTime t2 =0x3698;
//测试一下,比较两个对象是否相等,能不能使用"=="
// 这里的"=="判断的是:t1中保存的对象内存地址和t2中保存的对象内存地址是否相等
System.out.println(t1==t2);//false
//由此可见, 判断两个java对象是否相等,不能使用”==",因为=="比较的是两个对象的内存地址。
//重写equals之前(比较的是对象内存地址)
boolean flag=t1.equals(t2);
System.out.println(flag); //false
//重写equals之前(比较的是内容)
System.out.println(t1.equals(t2)); //true
MyTime t3=new MyTime(2008,8,9);
System.out.println(t3.equals(t1)); //false
}
}
class MyTime {
int year;
int month;
int day;
public MyTime() {
}
public MyTime(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public String toString() {
return this.year + "年" + this.month + "月" + this.day + "日";
}
//重写equals方法,如何重写?
//相同的返回值类型,方法名,形式参数列表
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof MyTime)) {
return false;
}
if (this == obj) {
return true;
}
// 当年相同,月相同,并且日也相同的时候,表示两个日期相同。两个对象相等
// 获取第一个日期的年月日
int year1 = this.year;
int month1 = this.month;
int day1 = this.day;
// 获取第二个日期的年月日
if (obj instanceof MyTime) {
MyTime t = (MyTime) obj;
int year2 = t.year;
int month2 = t.month;
int day2 = t.day;
if (year1 == year2 && month1 == month2 && day1 == day2) {
return true;
}
}
return false;
}
}
二、关于object类中的hashCode方法
- hashCode方法:在object中的hashcode方法:public native int hashCode () :
这个方法不是抽象方法,带有native关键字,底层调用c++程序 - hashcode() 方法返回的是哈希码:
实际上就是一个java对象的内存地址,经过哈希算法,得出的一个值。所以hashcode()方法的执行结果可以等同看做一个java对象的内存地址。 - 测试代码:
public class Test {
public static void main(String[] args) {
Object o = new Object();
int hashCodeValue = o.hashCode();
// 对象内存地址经过哈希算法转换的一个数字。可以等同看做内存地址。
System.out.println(hashCodeValue); //356573597
MyClass mc = new MyClass();
int hashCodeValue2 = mc.hashCode();
System.out.println(hashCodeValue2); //1735600054
}
}
class MyClass{
}