日期:2014-05-20  浏览次数:20772 次

看起来很简单的equals()问题,可就是不明白
最近在自学java,看得是张孝祥的书。
恳求大哥大姐们帮忙啊,困扰好久了!

以下是程序,
class   HashtableTest是测试Hashtable类的,通过自己编写的类对Hashtable的关键字和值分别返回。
class   MyKeyTest是测试equals()方法的,自己编写的覆盖Object中的equals

//   Date:   2007/1/4
//   From   page   229   and   141-142;


import   java.util.*;

class   MyKey
{
private String   name;
private   int   age;
public   MyKey(String   name,   int   age)
{
this.name   =   name;
this.age   =   age;
}
public   String   toString()
{
return   new   String(   name   +   ", "   +   age);
}


public   boolean   equals(Object   obj)/////////88
{
        //   MyKey   newObj   =   (MyKey)obj;
        //   if(name   ==   newObj.name   &&   age==newObj.age);
       
        //public   boolean   equals(MyKey   obj)  
        //if(name.equals(obj.name)   &&   age==obj.age)
       
                  if(name.equals(((MyKey)obj).name)   &&   age==((MyKey)obj).age)///99
return   true;               //   name.equals()调用的是谁的equals()??
      else
return   false;  
}


public   int   hashcode()
{
return   (name.hashCode()   +   age);
}
}

class   HashtableTest
{
public     void   test()
{
Hashtable   numbers   =   new   Hashtable();
numbers.put(new   MyKey( "ZhangSan ",18),new   Integer   (1));  
numbers.put(new   MyKey( "LiSi ",19),new   Integer   (2));
numbers.put(new   MyKey( "WangWu ",20),new   Integer   (3));
Enumeration   e   =   numbers.keys();
while(e.hasMoreElements())
{
MyKey   key   =   (MyKey)e.nextElement();
System.out.print(key.toString()   +   "   =   ");
System.out.println(numbers.get(key));      
4444   //   get(key)输出的顺序不是put()时候的顺序,并且输出顺序还不固定??
System.out.println(key.hashcode());
}                        
//   得到关键字Key
Enumeration   f   =   numbers.elements();
while(f.hasMoreElements())
{
  Integer   ele   =   (Integer)f.nextElement();
  System.out.println(ele.intValue());
} }
//   得到值Value
}
}

class   MyKeyTest
{
MyKey   p   =   new   MyKey( "LaoLi ",30);
MyKey   q   =   new   MyKey( "LaoLi ",30);
public void   test()
{
if(p.equals(q))
          System.out.println( "p   =   q ");
else
    System.out.println( "p   !=   q ");
}
}
public   class   HashTable_Equals_Test
{
public   static   void   main(String[]   args)
{
HashtableTest   hashTest   =   new   HashtableTest();