How to Make Your Own Class Key to a Map

Asked 1 years ago, Updated 1 years ago, 223 views

Do you ever specify your own class in the map key as follows?
However, self-made classes do not override equals and hashCode and
It's just like using a reference address as a key.

Person p1 = new Person("AAA", 10);
Person p2 = new Person("BBB", 20);

Map<Person, Boolean>map=new LinkedHashMap<>();
map.put(p1, true);
map.put(p2, false);

map.get(p1);
map.get(p2);

java

2022-09-30 22:04

1 Answers

Am I correct in understanding that the key to map in large development sites such as enterprises and open source projects is self-made?

"If we understand each other, the answer is "" (should be*)"" which is used countless times."
統計 I didn't take statistics, so I'm blurring it, but I've seen multiple source codes that make my class the key to Map.

Do not override equals unless otherwise required.
For example, if you want equals to be true for instances with the same name and age variables in the Person class, you do not need to use the inheritance equals method.


2022-09-30 22:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.