对于对象比较使用equals()方法的重要性,这里以String类为例进行了比较。
/**
* 对于对象比较使用equals()方法的重要性,这里以String类为例进行了比较。
* @author HAN
*
*/
public class TestEqual {
public TestEqual(){
testMethod();
}
void testMethod(){
String str=new String("Gaowen HAN");
String str2=new String("Gaowen HAN");
String str3="Gaowen HAN";
String str4="Gaowen HAN";
if(str.equals(str2)){
System.out.println("str is equal to str2");
}else{
System.out.println("str is not equal to str2");
}
if(str3==str4){
System.out.println("str is equal to str2");
}else{
System.out.println("str is not equal to str2");
}
if(str==str2){
System.out.println("str is equal to str2");
}else{
System.out.println("str is not equal to str2");
}
if(str.equals(str3)){
System.out.println("str is equal to str2");
}else{
System.out.println("str is not equal to str2");
}
if(str==str3){
System.out.println("str is equal to str2");
}else{
System.out.println("str is not equal to str2");
}
}
public static void main(String[] args) {
new TestEqual();
}
}
本文通过几个具体的示例,展示了在Java中使用equals方法进行对象比较的重要性和必要性,特别是针对String类,揭示了直接使用==和使用equals方法的区别。
1339

被折叠的 条评论
为什么被折叠?



