閱讀960 返回首頁    go 阿裏雲 go 技術社區[雲棲]


張孝祥JAVA就業培訓指南229頁錯誤代碼:關於HashTable我的糾正

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)
 {
  if(obj instanceof MyKey)
  {
   MyKey objTemp = (MyKey)obj;
   if(name.equals(objTemp.name) && age==objTemp.age)
   {
    return true;
   }
   else
   {
    return false;
   }
  }
  //假如obj不是MyKey類的實例對象,它就不可能與當前對象相等了
  else 
  {
   return false;
  }
 }
 public int hashCode()
 {
  return name.hashCode() + age;
 }
}

public class HashtableTest
{
 public static void main(String[] args)
 {
  Hashtable numbers=new Hashtable();
  numbers.put(new MyKey("zhangsan",18),new Integer(1));
  numbers.put(new MyKey("lisi",15),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).toString());
  }
 }
}


紅色部分或者這麼寫

public boolean equals(Object obj)

{

    MyKey mk=null;

if(obj instanceof MyKey)

mk=(MyKey)obj;

else

return false;

if(name.equals(this.name)&&age==this.age)

return true;

else

return false;

}



嘎嘎



最後更新:2017-04-02 22:16:32

  上一篇:go myeclipse+tomcat中出現org.apache.juli.logging.LogFactory以及ECLIPSE裏org.apache.catalina.startup.Bootstrap
  下一篇:go Linq中更新操作的思路