Java Reference
In-Depth Information
The
add
method was invoked six times on
set
, but the
HashSet
only contains four
elements because duplicate elements are not added. Because we are using generics, only
Product
objects can be added to
set
based on its construction on line 11.
Another
Set
implementation is
LinkedHashSet
, which is basically identical to
HashSet
except the insertion order is maintained behind the scenes by a doubly linked list. The
iterator
method returns the set in the order the elements were inserted. For example, see
if you can determine the output of the following
LinkedHashSet
iterator that uses the same
four
Product
objects from the previous code example:
Set<Product> linkedset = new LinkedHashSet<Product>();
linkedset.add(two);
linkedset.add(three);
linkedset.add(null);
linkedset.add(two);
linkedset.add(four);
linkedset.add(one);
Iterator<Product> products = linkedset.iterator();
while(products.hasNext()) {
System.out.println(products.next());
}
The
linkedset
object maintains the insertion order, so the iterator outputs the four
unique
Product
objects in the order that they were added:
202 Television
303 Cellphone
null
101 PC
Inserting
two
a second time did not change
linkedset
. Adding
one
did not change the
linkedset
because
four
was already added and the
four
and
one Product
objects are
equal.
Another
Set
implementation in the Collections Framework is
TreeSet
, useful for
working with large sets of data that require multiple searches or insertions. The
TreeSet
uses a tree data structure, so access is guaranteed in log(
n
) time, where
n
is the number
of elements in the tree. The
TreeSet
class also orders the elements in the set and contains
methods like
first
,
last
,
ceiling
, and
floor
for accessing specifi c elements and subsets.
Use
TreeSet
when your collection does not allow duplicates and you want control over
how the elements in the set are ordered.
Search WWH ::
Custom Search