这是我第一次使用这个网站,所以我道歉,如果我没有正确使用它。请一定让我知道。
不管怎样,我有一个帐户对象,它包含两个字符串.acctName和lastName (代码在下面)。
我想将这个对象插入到哈希表中,其中的键是acctName,我想使用多项式来减少碰撞。我听说必须重写hashCode()和equal方法。我相信我的重写是正确的,但我不确定它是否正确,因为它似乎没有被调用。有人能告诉我,如果我这样做是正确的(覆盖在正确的位置和正确的添加),并解释如何打印后添加?
感谢并期待着在未来为社会做出贡献!
类->帐户
public class Account
{
private String acctName;
private String lastName;
public Account(String acctName, String lastName)
{
this.acctName= acctName;
this.lastName= lastName
}
@Override
public int hashCode() {
return acctName.hashCode() + lastName.hashCode();
}
@Override
public boolean equals (Object otherObject) {
if (!(otherObject instanceof Account)) {
return false;
}
if (otherObject == this) {
return true;
}
Account accountHolder = (Account) otherObject;
return acctName.equals(accountHolder.acctName) && lastName.equals(accountHolder.lastName);
}类->驱动程序
public void insertInto()
{
Hashtable<String,Account> hash=new Hashtable<String,HoldInformation>();
Account account= new Account ("Deposit", "Jones");
Account account2= new Account ("Withdraw", "Smith");
hash.put ("deposit", account);
hash.put ("Withdraw", account2);
}在帐户对象中使用GETTER编辑
public String testGetter()
{
return acctName.hashCode() + lastName.hashCode();
}发布于 2012-12-08 03:02:18
密钥字段的HashCode用于散列。您正在使用字符串作为键,并为您的自定义类实现哈希代码。这就是为什么没人叫它。
发布于 2012-12-08 03:10:33
你做了几件不像你想的那样的事。您正在使用字符串作为与对象无关的键。这与您想要用作帐户名的字符串并不重要(这实际上不是因为您的大写),但您也是通过使用相同的键两次覆盖哈希映射中的对象(您已经映射不再存储帐户了,只有account3)。
在我看来,您想要使用集合而不是Map。
发布于 2012-12-08 03:22:40
如果您没有任何重复的帐户名称,那么使用每个帐户的名称作为映射键是非常好的。
您的hashCode()方法没有被调用,因为您没有使用帐户对象作为键:您使用的是String。
下面是如何使用它的accountName在地图中放置一个帐户:
Account accountOne = new Account("checking", "Smith");
Account accountTwo = new Account("saving", "Jones");
Map<String, Account> accountMap = new HashMap<String, Account>();
accountMap.put(accountOne.getAcctName(), accountOne);
accountMap.put(accountTwo.getAcctName(), accountTwo);请注意,您必须实现Account.getAccntName(),如下所示:
public String getAccttName() {
return acctName;
}顺便说一句,看起来您已经完成了很好的工作,覆盖了hashCode()和equals()。
还有..。欢迎来到StackOverflow。
https://stackoverflow.com/questions/13774006
复制相似问题