Java Reference
In-Depth Information
In Listing5-3 ' s TreeSetDemo application,Ididnotadd null tothe fruits array
because TreeSet throws NullPointerException when it detects an attempt to
addthiselement.Incontrast, HashSet permits null tobeadded,whichiswhy List-
ing 5-4 includes null in HashSetDemo 's fruits array.
When you run this application, it generates unordered output such as the following:
ss: null grapes bananas kiwis pears apples
Suppose you want to add instances of your classes to a hashset. As with String ,
your classes must override equals() and hashCode() ; otherwise, duplicate class
instancescanbestoredinthehashset.Forexample, Listing5-5 presentsthesourcecode
toanapplicationwhose Planet classoverrides equals() butfailstoalsooverride
hashCode() .
Listing 5-5. A custom Planet class not 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