Topic: 请问 Hashtable.containsKey(Object) 是怎样实现的?

  Print this page

1.请问 Hashtable.containsKey(Object) 是怎样实现的? Copy to clipboard
Posted by: dm356
Posted on: 2005-09-27 20:16

下面这段代码:很是奇怪
import java.util.*;

public class Hashtabletest {

  public static void main(String args[])
  {
    Hashtable hs = new Hashtable();
    for(int i = 0; i < 10; i++)
      hs.put(new Integer(i), new String(i + "aa"));
    
    if(hs.containsKey(new Integer(0)))
      System.out.println("OK");
    else
      System.out.println("SORRY");
    
    System.out.println((new Integer(1)) == (new Integer(1)));
    
    Hashtable hs1 = new Hashtable();
    for(int i = 0; i < 10; i++)
      hs1.put(new hashelement(i), new String(i + "aa"));
    
    if(hs1.containsKey(new hashelement(0)))
      System.out.println("OK");
    else
      System.out.println("SORRY");
  }
}

class hashelement
{
  int n = 0;
  hashelement(int i)
  {
    n = i;
  }
}

结果是:
OK
false
SORRY
为什么Integer与自定义的类不同产生的结果不同,如果想使自定义的类也作出Integer的结果,怎样修改自定义的类?

请各位赐教!

2.Re:请问 Hashtable.containsKey(Object) 是怎样实现的? [Re: dm356] Copy to clipboard
Posted by: bluecrystal
Posted on: 2005-09-28 00:10

1 Integer对象的比较用equals或者compareTo;
2 To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method 这是jdk文档的原话,通常要实现hashCode和equals方法
下面简单给出修改后的代码

import java.util.*;

public class Hashtabletest {

public static void main(String args[])
{
Hashtable hs = new Hashtable();
for(int i = 0; i < 10; i++)
hs.put(new Integer(i), new String(i + "aa"));

if(hs.containsKey(new Integer(0)))
System.out.println("OK");
else
System.out.println("SORRY");

  System.out.println((new Integer(1)).equals(new Integer(1)));

Hashtable hs1 = new Hashtable();
for(int i = 0; i < 10; i++)
hs1.put(new hashelement(i), new String(i + "aa"));

if(hs1.containsKey(new hashelement(0)))
System.out.println("OK");
else
System.out.println("SORRY");
}
}

class hashelement
{
int n = 0;
hashelement(int i)
{
n = i;
}
public int getN() {
   return n;
}
public boolean equals(Object hs) {
   return (this.n == ((hashelement)hs).getN());
}
public int hashCode() {
   return n;
}
}


运行结果为:

OK
true
OK


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923