EffieR

最符合理智的莫过于对理智的否定

 

equals & ==

1.  先了解:string a=new string("EffieR"); 表示一定要分配内存string对象,还有相应的引  用。string b="EffieR",此时就不再分配内存,而是建立一个新的引用b指向同一个对象"EffieR".
 
例如:
public class TestOne
 {
    public static void main(String[] args) {
        String s1 = "Monday";
        String s2 = "Monday";
        if (s1 == s2)
            System.out.println("s1 == s2");
        else
            System.out.println("s1 != s2");
    }
}


2. 如果是两个新的对象(new),内存肯定不同,那么引用比较时也不相同。
    而调用equals时则是比较对象的内容,可实现我们的内容比较。
例如:
public class  Testtwo
{
 public static void main(String[] args)
 {
   String a=new String("foo");
         String b=new String("foo");
  
   System.out.println("==:"+ (a==b) );
   System.out.println("equals: "+ a.equals(b));
  
  
 }
}

3. string.intern(); 来释放相同值的string内存

例如:
public class TestThree
{

 /**
  * @param args
  */
 public static void main(String[] args)
 {
  // TODO Auto-generated method stub
   String a="foo";
  
         String b=new String("foo").intern();
  
   System.out.println("==:"+ (a==b) );
   System.out.println("equals: "+ a.equals(b));
  

 }

}

4. 测试直接继承Object的方法equals()

 例如:
class testEquals
{
 testEquals()
 {
  System.out.println("testEquals object");
 }

};
 
public class  TestFour
{
 public static void main(String[] args)
 {
  
  
         testEquals e1=new testEquals();
   testEquals e2=new testEquals();
   System.out.println(e1.equals(e2));
   
 }
}

5. 创建自己的类,覆盖equals()


例如:

class testEquals2
{
    private int a;
 testEquals2(int p)
 {
  
  a=p;
  
 }
 public int getMember()
 {
  return this.a;
 }
 public boolean equals(testEquals2 ob)
 {
  int a,b;
  a=this.getMember();
  b=ob.getMember();
     return a==b;
 }
};

public class TestFive
{
 public static void main(String[] args)
 {
      testEquals2 e3=new testEquals2(11);
   testEquals2 e4=new testEquals2(11);
   System.out.println(e3.equals(e4));
 }
}

6...

posted on 2006-04-29 13:38 EffieR 阅读(618) 评论(0)  编辑  收藏 所属分类: 学习和技术


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

文章档案

相册

deep world

搜索

最新评论

阅读排行榜

评论排行榜