wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hashmap Confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Hashmap Confusion" Watch "Hashmap Confusion" New topic
Author

Hashmap Confusion

Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 598

From K&B SelfTest pg 637 question 4


Concerning the following:



Now isn't it true that "A hashmap can contain one null key,and multiple null values."?So then why wouldn't t2 be added to the collection?


===>SCJP 1.5(72%)<===
==>SCWCD1.5(76%)<===
Rajshekhar Paul
Ranch Hand

Joined: Oct 17, 2006
Posts: 140
I am not able to get your question. Can you elaborate a bit?


When it's obvious that you have to do it, just do it without shattering your thoughts over different directions.
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
Are you sure what you are saying and the program you have typed is complete and contains no error.

I run your program, it has this problem

return ((ToDos)0).day == this.day;

what is this zero 0, it should be o.

and second you have commented hashcode() function in ToDos?
Can I ask why have you commented, if you run this code without hashcode() it will add t2, as your program is adding.

But if you run this code with given hashcode it will not add t2.
Why?
Answer is How hashmap works ?
1. If you add any object in hashmap, hashmap will check its hashcode, for t2 hashcode in your program is 9. That is of t1 also.
2. Now if two objects have same hashcode than hashmap will call equals() method, t1.equals(t2) that is "Monday"=="Monday" that will return true. . If equals() return true, it will see t2 as duplicate of t1, so t2 will not be added, as HashMap does not contain duplicate keys.


SCJP 6
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
Now isn't it true that "A hashmap can contain one null key,and multiple null values."?So then why wouldn't t2 be added to the collection?


And please tell me what is relationship of this statement with the given program?
Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 598

OK I understand...

I thought that duplicate keys could be added to the collection...but that they just wouldn't be able to retrieve the object.

The relationship of that statement is that I was confused between the rules for duplicates and the rules for null values
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hashmap Confusion
 
Similar Threads
S & B SCJP 6 - C7 - Q4 erratum
HashMap Duplicate Element Problem
How to write toString method to display name of Object
HashMap and hashCode()
Detecting Duplicates in Hashmap