- 1 java中的“==”的用法
- 对于基本类型(byte,short,int,char,long, float,double,boolean):
比较的是两者的值是否相同 - 对于引用类型(类类型,接口类型,数组类型):
比较的是两者的地址值是否相同
- 2 没有重写的equals()方法
public class EqualsTest {
public static void main(String[] args) {
objectDemo1 od1 = new objectDemo1();
objectDemo1 od2 = new objectDemo1();
objectDemo1 od3 = od1;
System.out.println(od1.equals(od2));
System.out.println(od1.equals(od3));
System.out.println(od2.equals(od3));
}
}
- 3 重写后的equals()方法
重写之后,比较的就是对象的成员变量值
/*
* @Override
* public boolean equals(Object obj) {
* if (this == obj)
* return true;
* if (obj == null)
* return false;
* if (getClass() != obj.getClass())
* return false;
* objectDemo1 other = (objectDemo1) obj;
* if (age != other.age)
* return false;
* if (name == null) {
* if (other.name != null)
* return false;
* } else if (!name.equals(other.name))
* return false;
* return true;
* }
*/
public class EqualsTest2 {
public static void main(String[] args) {
objectDemo1 od1 = new objectDemo1();
objectDemo1 od2 = new objectDemo1();
objectDemo1 od3 = od1;
System.out.println(od1.equals(od2));
System.out.println(od1.equals(od3));
System.out.println(od2.equals(od3));
}
}