== 与 equlas
1. ==
1.1 基本数据类型比较值
1.2 引用数据类型比较引用地址
public class EqualsTest { public static void main(String[] args) { Person tom = new Person(1, "Tom"); Person tom1 = new Person(1, "Tom"); System.out.println(tom == tom1); System.out.println(1 == 1); } }
结果:
false true
2. equlas
2.1 equlas 中的源代码
object:
public boolean equals(Object obj) { return (this == obj); }
Integer:
public boolean equals(Object obj) { if (obj instanceof Integer) { return value == ((Integer)obj).intValue(); } return false; }
String:
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
2.2 代码实战
public class EqualsTest { public static void main(String[] args) { Person tom = new Person(1, "Tom"); Person tom1 = new Person(1, "Tom"); System.out.println(tom.equals(tom1)); Integer a = 1; System.out.println(a.equals(1)); String s = "Tom"; System.out.println(s.equals("Tom")); } }
结果:
false true true
public class EqualsTest {
public static void main(String[] args) {
Person tom = new Person(1, "Tom");
Person tom1 = new Person(1, "Tom");
System.out.println(tom.equals(tom1));
}
}