Hello,
Thank you for your time!
I have a Hashmap that has keys of of type Account (custom class) and the values are strings. The Account class has the following private variables:
1) name (String type)
2) account number (String type)
3) balance (type double).
Following are the files:
public class Account implements
{
private String name, a_number;
private double balance;
public Account (String name, String a_number, double balance)
{
this.name = name;
this.a_number = a_number;
this.balance = balance;
}
public String getName()
{
return name;
}
public String getANumber()
{
return a_number;
}
public double getBalance()
{
return balance;
}
@Override
public boolean equals(Object a)
{
if (a == null)
{
return false;
}
else
{
Account temp = (Account) a;
if (this.name.equals(temp.name))
{
return true;
}
else
{
return false;
}
}
}
@Override
public int hashCode()
{
return name.hashCode();
}
}
import java.util.HashMap;
import java.util.HashSet;
public class Maps
{
private HashMap <Account, String> map;
public Maps()
{
map = new HashMap <Account, String>();
createMap();
}
public void createMap()
{
map.put (new Account ("A", "14243", 46778), "444");
map.put (new Account ("A", "142463", 677489), "23");
HashSet <Account> hs = new HashSet<Account> ( map.keySet());
for (Account s : hs)
{
if (map.get(s).equals("23"))
{
System.out.println (s.getName() + " " + s.getANumber() + " " + s.getBalance());
}
}
Account c = new Account ("A", "14243", 46778);
System.out.println ("Value for Account c = " + map.get(c));
}
public static void main( String args[] )
{
Maps w = new Maps();
}
}
My Question:
When I ran this program, I expected the output to be:
A, 142463, 677489
but, I am getting the following output:
A 14243 46778.0
My understanding was that when a duplicate key is added (as defined in the equals() method) to a hash map, it replaces the old (key,value) pair.
I then recreated the old Account object and tried to get its key value. The output was as below:
A 14243 46778.0
Value for Account c = 23
That is, its keeping the old key (A 14243 46778.0), but replacing its previous value (444) with the value of the newly added Account (23).
Also, when I check for "444" in the map, I am no longer able to obtain the corresponding key as it has been replaced with 23.
I would be grateful in any help in fixing this issue.
Thank you!"