Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtable overriding

Tags:

java

android

This is my first time using this website so I apologize if I am not using it correctly. Please do let me know.

Anyway I have an Account object that takes in 2 strings... An acctName, and lastName (Code is below).

I want to insert this object into a hash table with the key being the acctName and I would like to use polynomials for reducing collision. I have heard that I must override hashCode() and equal method. I believe I have overridden correctly but I am not sure it is correct because it seems to not be called. Can someone tell me if I am doing this right (Overriding in the right location and adding correctly) and explain to me how to print after an add?

Thanks and looking forward to contributing to the community in the future!

Class---> Account

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);
}

Class----> Driver

 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);

 }

EDIT WITH GETTER INSIDE Account Object

   public String testGetter()
  {

     return acctName.hashCode() + lastName.hashCode();
    }
like image 204
michael Avatar asked Nov 13 '22 15:11

michael


1 Answers

HashCode of the key field is used for hashing. You are using string as key, and implementing hashcode for you custom class. that's why it is been not called.

like image 131
Debobroto Das Avatar answered Nov 15 '22 07:11

Debobroto Das