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

5th Apr 2017, 8:20 PM
Sbk0103
Sbk0103 - avatar
11 Antworten
+ 1
No need to override anything. it will work
5th Apr 2017, 8:33 PM
Edward
+ 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");
5th Apr 2017, 8:35 PM
Edward
+ 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"
5th Apr 2017, 8:45 PM
Edward
+ 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
5th Apr 2017, 8:48 PM
Edward
+ 1
ok yea then you should override equals() and hashcode ()
5th Apr 2017, 8:55 PM
Edward
+ 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 ?
5th Apr 2017, 8:59 PM
Sbk0103
Sbk0103 - avatar
+ 1
i havent tried it so dont trust me 100%. but it would make sense to override hashcode and equals
5th Apr 2017, 9:02 PM
Edward
0
just use the class name as the key so HashMap <Student, Value>
5th Apr 2017, 8:30 PM
Edward
0
Do u think it would work... i mean do I need to override.. equals and hasCode method in Student class ?
5th Apr 2017, 8:32 PM
Sbk0103
Sbk0103 - avatar
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
5th Apr 2017, 8:38 PM
Sbk0103
Sbk0103 - avatar