Let's say I have a class called City, which stores some data about a city:
public class City {
String [] states;
String name;
double lat, lng;
//Constructors, getters/setters, etc
}
I want to keep a list of cities without duplicates. Now normally it would be easy (use a HashSet) but I will be comparing two objects which are technically distinct (different memory addresses) but the same String and double values. I want my HashSet to consider objects with the same inner values to be 'equivalent'.
I can't seem to figure out how to do this. Do I override the hashCode() method? Or perhaps I override the equals() method?
Would something like the following work?
public int hashCode() {
return (double) name.hashCode() + lat * 100 + lng;
}
Simply use a Set and redefine for your class City
both the methods:
Remember that it is always a good practice to redefine equals and hashcode and that is not possible to redefine only one of them without having strange behaviours in data structures like HashSet
and HashMap
.
Note: the Set
is the right data structure, because as for definition:
A collection that contains no duplicate elements . More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
You should just override equals
and hashCode
while comparing the actual values for your String
and double
values in equals
, and base your hash on those in your hashCode
method.
In the implementation you display, the hash might be weak - you probably want to use a prime seed.
When implemented as recommended, equals
and hashCode
will compare your objects and place them in buckets based on the values of their members, which is what you would typically want.
If you are using an IDE (which is recommended), you can let the IDE draft those methods for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.