JAVA中equals()方法的重要性
对于对象比较使用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(); } }