File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hashmap Confusion

 
Duran Harris
Ranch Hand
Posts: 608
Eclipse IDE Spring Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Rajshekhar Paul
Ranch Hand
Posts: 140
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not able to get your question. Can you elaborate a bit?
 
Punit Singh
Ranch Hand
Posts: 952
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Punit Singh
Ranch Hand
Posts: 952
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 608
Eclipse IDE Spring Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic