0
Passing Class object as a key in HashMap in java
How can we set Class object as a key in HashMap. Suppose I have one class "Student" with two fields "rollNo" and "name". I need to pass object of this class as key in HashMap.How can I do that. Thanks
11 Answers
+ 1
No need to override anything. it will work
+ 1
then when you wanna use it. lets just say your value is a string
HashMap<Student, String> map =
new HashMap<>();
Student student = new Student ();
map.put (student, "Student1");
+ 1
Student student1 = new Student ();
Student student2 = new Student ();
map.put (student1, "Test1");
map.put (student2, "Test2");
map.put (student1, "Test3");
the map now has 2 entries, since student1 was detected as a duplicate, it overrides the first one. so now map.get (student1); will give you "Test3"
+ 1
another example
Student student1 = new Student ();
map.put(student1, "Test1");
Student student2 = student1;
map.put (student2, "Test2");
remember student1 is just a reference to the object. so setting student2 = student1 also points student2 to the same reference as student1, therefore the second map.put () overrides the first, and now the only entry in the map is Key: student2, Value: Test2
+ 1
ok yea then you should override equals() and hashcode ()
+ 1
Many thanks Edward.. but have u tried your solutions or u r really agree with overriding equals and hasCode method.. I really need to understand it properly ?
+ 1
i havent tried it so dont trust me 100%. but it would make sense to override hashcode and equals
0
just use the class name as the key so
HashMap <Student, Value>
0
Do u think it would work... i mean do I need to override.. equals and hasCode method in Student class ?
0
But still i have one doubt regarding HashMap behaviour..
As it wont allow duplicate keys so in this case how it would identify the key is duplicate..
I mean passing multiple object of Student class as a key..
got my point