這是一個很簡單,但卻是像我這樣的初學者很容易混淆的問題。作為初學者想要理解某一問題 ,以我之見,就是動手編個程序。
= =和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));
}
}
結果為:result==
true
總結一下:
但是“= =“操作符并不涉及到對象內容的比較,只是說這兩個對象是否為同一個。而對象內容的比較,正是equals方法做的事。
posted on 2007-04-17 13:35
靜兒 閱讀(735)
評論(3) 編輯 收藏