Java Reference
In-Depth Information
application (
java CustomClassAndHashSet
). You will observe output (similar
to that shown below) that reveals no duplicate elements:
true
[Saturn, Earth, Uranus, Fomalhaut b, 51 Pegasi b, Venus,
Jupiter, Mercury, Mars, Neptune]
Note
LinkedHashSet
is a subclass of
HashSet
that uses a linked list to store
itselements.Asaresult,
LinkedHashSet
'siteratorreturnselementsintheorderin
which they were inserted. For example, if
Listing 5-4
had specified
Set<String>
ss = new LinkedHashSet<>();
,theapplication'soutputwouldhavebeen
ss:
apples pears grapes bananas kiwis null
. Also,
LinkedHashSet
offers slower performance than
HashSet
and faster performance than
TreeSet
.
EnumSet
Chapter 3
introduced youtotraditional enumerated typesandtheir enumreplacement.
(An enum is an enumerated type that is expressed via reserved word
enum
.) The fol-
lowing example demonstrates the traditional enumerated type:
static final int SUNDAY = 1;
static final int MONDAY = 2;
static final int TUESDAY = 4;
static final int WEDNESDAY = 8;
static final int THURSDAY = 16;
static final int FRIDAY = 32;
static final int SATURDAY = 64;
Although the enum has many advantages over the traditional enumerated type, the
traditionalenumeratedtypeislessawkwardtousewhencombiningconstantsintoaset;
for example,
static final int DAYS_OFF = SUNDAY | MONDAY;
.
DAYS_OFF
is an example of an integer-based, fixed-length
bitset
, which is a set of
bitswhereeachbitindicatesthatitsassociatedmemberbelongstothesetwhenthebit
is set to 1, and is absent from the set when the bit is set to 0.
Note
An
int
-basedbitsetcannotcontainmorethan32membersbecause
int
has
asizeof32bits.Similarly,a
long
-basedbitsetcannotcontainmorethan64members
because
long
has a size of 64 bits.