若是是比較基本數據類型的只須要比較值就能夠java
int a = 1; long b = 1l; double c = 1; System.out.println(a==b); System.out.println(b==c); true true
二者比較的都是地址值,this
Student student1 = new Student(); Student student2 = new Student(); System.out.println(student1.equals(student2)); System.out.println(student1 == student2); false false
很容易理解,兩對象的地址值不一樣,因此都爲false。code
再來看一段代碼對象
String s1 = "abc"; String s2 = "abc"; System.out.println(s1==s2); System.out.println(s1.equals(s2)); System.out.println("------------"); String s3 = "abc"; String s4 = new String("abc"); System.out.println(s3==s4); System.out.println(s3.equals(s4)); System.out.println("---------------"); String s5 = new String("abc"); String s6 = new String("abc"); System.out.println(s5==s6); System.out.println(s5.equals(s6)); true true ------------ false true --------------- false true
string類有點特殊,string s4 = "abc";,也至關於String s4 = new String("abc");代碼中s1==s2,是由於當定義string s2 = "abc"以前s1已經存在常量池中,因此s2直接指向了s1。這就使得s1==s2的返回值爲true。打開string類的equals方法,源碼是被重寫了的,源碼
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;
對象地址相同直接返回true,string