Java Reference
In-Depth Information
views in the collections api
6.10
In Section 6.8, we saw an illustration of methods that return “views” of a map.
Specificially,
keySet
returns a view representing a
Set
of all keys in the map;
values
returns a view representing a
Collection
of all values in the map;
entrySet
returns a view representing a
Set
of all entries in the map. Changes to the map
will be reflected in any view, and changes to any view will reflect on the map
and also the other views. This behavior was demonstrated in Figure 6.38 by
using the
remove
method on the key set and value collection.
There are many other examples of views in the Collections API. In this
section, we discuss two such uses of views.
6.10.1
the
subList
method for
List
s
The
subList
method takes two parameters representing list indices and returns
a view of a
List
whose range includes the first index and excludes the last
index. Thus,
System.out.println( theList.subList( 3, 8 ) );
prints the five items in the sublist. Because
subList
is a view, nonstructural
changes to the sublist reflect back in the original, and vice-versa. However, as
is the case with iterators, a structural modification to the original list invali-
dates the sublist. Finally, perhaps most importantly, because the sublist is a
view, and not a copy of a portion of the original list, the cost of invoking
subList
is
O
( 1 ), and the operations on the sublist retain their same efficiency.
6.10.2
the
headSet
,
subSet
, and
tailSet
methods for
SortedSet
s
The
SortedSet
class has methods that return views of the
Set
:
SortedSet<AnyType> subSet(AnyType fromElement, AnyTypet toElement);
SortedSet<AnyType> headSet(AnyType toElement);
SortedSet<AnyType> tailSet(AnyType fromElement);
fromElement
and
toElement
in effect partition the
SortedSet
into three subsets:
the
headSet
,
subSet
(middle part), and
tailSet
. Figure 6.42 illustrates this by
partitioning a number line.
In these methods,
toElement
is not included in any range, but
fromElement
is. In Java 6, there are additional overloads of these methods that allow the
caller to control whether
fromElement
and
toElement
are included in any par-
ticular range.
Search WWH ::
Custom Search