Hashtable键获取错误的值

时间:2010-11-24 02:58:48

标签: java

import java.util.*;

public class HashingTest {

 // instance variables

 String name;
 int age;
 int hashCd;
 String gender;

 public HashingTest(String nm, int age, String gend)
 {
  name = nm;
  this.age = age;
  gender = gend;
 }


 public static void main(String[] args) {

  HashingTest person1 = new HashingTest("Durvi",5,"Female");
  HashingTest person2 = new HashingTest("Pillu",5,"Female");
  HashingTest person3 = new HashingTest("Ninad",5,"Male");
  HashingTest person4 = new HashingTest("Varun",5,"Male");
  HashingTest person5 = new HashingTest("Sapna",5,"Female");
  HashingTest person6 = new HashingTest("Priya",5,"Female");

  //person2 and person1 are now referring to the same object
  person2 = person1;

  boolean truth = person1.equals(person2);

  System.out.println(truth + " : Which means that if two object varaibles are refering the same object the equals() method returns true" );

  Hashtable<HashingTest, String> hs = new Hashtable<HashingTest, String>();
  hs.put(person1, "Durvi");
  hs.put(person2, "Pillu");
  hs.put(person3, "Ninad");
  hs.put(person4, "Varun");

  String personVal = (String)hs.get(person1); 

  System.out.println(personVal);

 }
}

输出::

true:这意味着如果两个对象变量引用同一个对象,则equals()方法返回true Pillu

5 个答案:

答案 0 :(得分:2)

这是按预期工作的。你在做什么是这样的:

person2 = person1;

hs.put(person1, "Durvi");
hs.put(person2, "Pillu"); // since person1 == person2, 
                          // this overwrites the previous key

String personVal = (String)hs.get(person1);

person2 == person1以来,最后一次通话等于

String personVal = (String)hs.get(person2); // person1 == person2

作为旁注,您需要为equals()课程实施hashCode()HashingTest,请点击此处:

答案 1 :(得分:0)

在这种情况下你得到了正确的行为,但是......

你不能指望你做了什么才能正常工作,因为你没有被覆盖 hashcode()equals()

因为你正在创建一个类,其实例被用作哈希容器中的键(如 HashSetHashMapHashTable),您必须覆盖hashcode()equals()

http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

答案 2 :(得分:0)

默认情况下,来自Object的java的equals方法将比较引用。由于您将引用设置为相同然后是,因此对'equals'的调用将返回true。如果您希望更改该行为,则需要覆盖等于检查字段值(以及您需要的任何其他内容)。

当你这样做时要小心 - 我建议你阅读Josh Bloch在有效的java中所说的内容:

Item 8: Obey the general contract when overriding equals
Item 9: Always override hashCode when you override equals

答案 3 :(得分:0)

看到你将person1和person2变量设置为同一个对象,

  hs.put(person1, "Durvi");
  hs.put(person2, "Pillu");

相当于

  hs.put(person1, "Durvi");
  hs.put(person1, "Pillu");

答案 4 :(得分:0)

了解在Hashtable中,您已使用对象引用作为键,并使用String作为值。

person1和person2都指向main方法中的同一个对象,即

创建的对象
HashingTest("Durvi, 5, Female")

hs.put(person1, "Durvi");
hs.put(person2, "Pillu");

上面的第一个put语句创建一个对象引用为“Durvi”的条目,并为其赋值“Durvi”。

由于Hashtables中的键不能重复,第二行会将前一行创建的值“Durvi”替换为“Pillu”..

所以当你执行get方法

String personVal = (String)hs.get(person1);
 //returns the value "Pillu" which the key person1 now refers to in the hash table.
System.out.println(personVal); //prints "Pillu"

我希望我已经说清楚了...... 如果您需要进一步澄清,请回来......

请注意,您已使用对象引用代替“key”。我希望你没有错误地做到这一点