Java Reference
In-Depth Information
Solution
Use a
Set
implementation instead of a
List
(e.g.,
Set<String> myNames = new
HashSet<>()
).
Discussion
contains()
,
size()
,
isEmpty()
, and the like. The differences are that it does not preserve
order; instead, it enforces uniqueness—if you add the “same” item (as considered by its
equals()
method) twice or more, it will only be present once in the set. For this reason, the
index-based methods such as
add(int, Object)
and
get(int)
, are missing from the
Set
implementation: you might “know” that you've added seven objects but only five of those
were unique, so calling
get()
to retrieve the sixth one would have to throw an
ArrayIn-
dexOutOfBoundsException
! Better that you don't think of a
Set
as being indexed.
WARNING
As the Java 7
Set
document states: “Note: Great care must be exercised if mutable ob-
jects are used as set elements. The behavior of a set is not specified if the value of an ob-
ject is changed in a manner that affects equals comparisons while the object is an element
in the set. A special case of this prohibition is that it is not permissible for a set to contain
itself as an element.”
This code shows a duplicate entry being made to a
Set
, which will contain only one copy of
the strong
"One":
.
Set
<
String
>
hashSet
=
new
new
HashSet
<>();
hashSet
.
add
(
"One"
);
hashSet
.
add
(
"Two"
);
hashSet
.
add
(
"One"
);
// DUPLICATE
hashSet
.
add
(
"Three"
);
hashSet
.
forEach
(
s
->
System
.
out
.
println
(
s
));
Not surprisingly, only the three distinct values are printed.