File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes hashmap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "hashmap" Watch "hashmap" New topic
Author

hashmap

Edward Chen
Ranch Hand

Joined: Dec 23, 2003
Posts: 798
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

Joined: Nov 24, 2005
Posts: 14688
    
  16

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.


[My Blog]
All roads lead to JavaRanch
Edward Chen
Ranch Hand

Joined: Dec 23, 2003
Posts: 798
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

Joined: Nov 24, 2005
Posts: 14688
    
  16

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

Joined: Oct 27, 2005
Posts: 19719
    
  20

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()).


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashmap