判断基本数据类型,判断的是值是否相等
判断引用数据类型,判断的是地址是否相等
1:A a = new A();
A b = a;
A c = a;
a == b == c ;//true
equals()
是Object的方法,只能判断引用类型是否相等,默认判断的是地址是否相等
子类往往重写该方法,判断内容是否相等,比如Integer、String
Object的equals()
public boolean equals(Object obj) {
return (this == obj);
}
Integer的equals()
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
String的equals()
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
# 普通类equals()比较
class F{
private String name;
public F(String name){
this.name = name;
}
}
F f = new F("zs");
F f1 = new F("zs");
System.out.println(f.equals(f1));//false,普通类equals没有重写,调用的是Object的equals(),比较的是地址是否相等
重写equals()
@Setter
@Getter
public class Person {
private int a;
private String name;
@Override
public boolean equals(Object obj){
if(this == obj){
return true;
}
if(obj instanceof Person){
Person p = (Person) obj;
return this.getA() == p.getA() && this.getName().equals(p.getName());
}
return false;
}
public static void main(String[] args) {
Person p1 = new Person();
p1.setA(1);
p1.setName("1");
Person p2 = new Person();
p2.setA(1);
p2.setName("1");
System.out.println(p1.equals(p2));
}
}
1:10 == 10.0f //true
2:char a = 'A';
cahr b = 12; //a==b true
3:String a = new String("1");
String b = new String("1");
a == b //false
a.equals(b)//true
4:"A" == new Integer(1);//编译错误,因为不是同一个对象