= =和equals究竟有何區別?
程序1:
public class Test {
public String judge(String a, String b) {
if (a == b) {//如果a的內存地址等于b的內存地址,即a,b為同一個對象
return "true";
} else {
return "false";
}
}
public static void main(String args[]) {
String a = new String("foo");//創建一個對象,將為它分配一個新空間。
String b = new String("foo");
Test test = new Test();
System.out.println("result=="+test.judge(a, b));
}
}
結果為:result==false
程序2:
public class Test {
public String judge(String a, String b) {
if (a.equals(b) ) { //如果a字符串的值等于b字符串的值
return "true";
} else {
return "false";
}
}
public static void main(String args[]) {
String a = new String("foo");
String b = new String("foo");
Test test = new Test();
System.out.println("result=="+test.judge(a, b));
}
}
結果為:result==true
程序3:
public class Test {
public String judge(String a, String b) {
if (a==b) {
return "true";
} else {
return "false";
}
}
public static void main(String args[]) {
String a = "foo";//將a指向這個字符串,不為它分配空間。
String b = "foo";
Test test = new Test();
System.out.println("result=="+test.judge(a, b));
}
}
結果為:result==true
程序4:
public class Test {
public String judge(String a, String b) {
if (a.equals(b)) {
return "true";
} else {
return "false";
}
}
public static void main(String args[]) {
String a = "foo";
String b = "foo";
Test test = new Test();
System.out.println("result=="+test.judge(a, b));
}
}
總結一下:
但是“= =“操作符并不涉及到對象內容的比較,只是說這兩個對象是否為同一個。而對象內容的比較,正是equals方法做的事。