• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashmap

 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the hashmap, I intentionally return 1 as its hashcode, it will make an array of array as its implementation. Then add two Student with same name. When look up s1, it will equals to s2, not s1. why? and if I have to make it equals to s1, what change I should make ?

Thanks.

 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It equals s2 because s2 is put last into the map. At that time, there's already the same key in the map, so s2 overwrites it.
 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christophe Verré wrote: there's already the same key in the map, so s2 overwrites it.

when put into map, it are two different objects, s1, s2 as its key. Key should be different. That map should have two different object inside, no overwrite here. is it correct ?

And still one question, if we have to make s equals to s1, what should we do ?

Thanks.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Map cannot have two same keys. How does it know if two keys are equals ? By using equals() and hashCode(). Your two objects are equal, and use the same hashCode. So their can be only one of them in the Map.

And still one question, if we have to make s equals to s1, what should we do ?

You have to find a better way to store your students in a map. Don't make them equal just by their first name. Use other information, like student id.
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Side note: your equals method is broken. The equals method should return false when null or an object of an incompatible class is given as argument. In your case, s1.equals(null) will throw a NullPointerException instead of returning false; s1.equals("") will throw a ClassCastException. Before doing any casting in the equals method you should have checked for:
- the value being null (== null)
- the value being castable to the right type (instanceof, or the sometimes preferred getClass() == o.getClass()).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic