JAVA中equals()方法的重要性


对于对象比较使用equals()方法的重要性,这里以String类为例进行了比较。

  1. /** 
  2.  * 对于对象比较使用equals()方法的重要性,这里以String类为例进行了比较。 
  3.  * @author HAN 
  4.  * 
  5.  */  
  6. public class TestEqual {  
  7.     public TestEqual(){  
  8.         testMethod();  
  9.     }  
  10.     void testMethod(){  
  11.         String str=new String("Gaowen HAN");  
  12.         String str2=new String("Gaowen HAN");  
  13.         String str3="Gaowen HAN";  
  14.         String str4="Gaowen HAN";  
  15.   
  16.         if(str.equals(str2)){  
  17.             System.out.println("str is equal to str2");  
  18.         }else{  
  19.             System.out.println("str is not equal to str2");  
  20.         }  
  21.           
  22.         if(str3==str4){  
  23.             System.out.println("str is equal to str2");  
  24.         }else{  
  25.             System.out.println("str is not equal to str2");  
  26.         }  
  27.           
  28.         if(str==str2){  
  29.             System.out.println("str is equal to str2");  
  30.         }else{  
  31.             System.out.println("str is not equal to str2");  
  32.         }  
  33.           
  34.         if(str.equals(str3)){  
  35.             System.out.println("str is equal to str2");  
  36.         }else{  
  37.             System.out.println("str is not equal to str2");  
  38.         }  
  39.               
  40.         if(str==str3){  
  41.             System.out.println("str is equal to str2");  
  42.         }else{  
  43.             System.out.println("str is not equal to str2");  
  44.         }  
  45.           
  46.     }  
  47.     public static void main(String[] args) {  
  48.         new TestEqual();  
  49.     }  
  50. }         

相关内容