Java Reference
In-Depth Information
When you run this application, it generates unordered output such as the following:
[Venus, Fomalhaut b, Uranus, Mars, Neptune, Jupiter, Earth,
Mercury, Saturn, 51 Pegasi
b, 51
Pegasi b]
This output reveals two 51 Pegasi b elements in the hashset. Although these
elementsareequalfromtheperspectiveoftheoverriding equals() method(thefirst
outputline, true ,provesthispoint),overriding equals() isnotenoughtoavoiddu-
plicate elements being stored in a hashset: you must also override hashCode() .
Theeasiestwaytooverride hashCode() in Listing5-5 's Planet classistohave
theoverridingmethodcallthe name field's hashCode() methodandreturnitsvalue.
valid hashCode() method.) Listing5-6 presentsthisoverriding hashCode() meth-
Listing 5-6. A custom Planet class overriding hashCode()
import java.util.HashSet;
import java.util.Set;
class CustomClassAndHashSet
public static void main(String[] args)
Set<Planet> sp = new HashSet<>();
sp.add(new Planet("mercury"));
sp.add(new Planet("venus"));
sp.add(new Planet("earth"));
sp.add(new Planet("mars"));
sp.add(new Planet("jupiter"));
sp.add(new Planet("saturn"));
sp.add(new Planet("uranus"));
sp.add(new Planet("neptune"));
sp.add(new Planet("fomalhaut b"));
Planet p1 = new Planet("51 pegasi b");
Planet p2 = new Planet("51 pegasi b");
Search WWH ::

Custom Search