Java Reference
In-Depth Information
java.util.Collections
+
singleton(o: Object): Set
+
singletonList(o: Object): List
+
singletonMap(key: Object, value: Object): Map
+
unmodifiableCollection(c: Collection): Collection
+
unmodifiableList(list: List): List
+
unmodifiableMap(m: Map): Map
+
unmodifiableSet(s: Set): Set
+
unmodifiableSortedMap(s: SortedMap): SortedMap
+
unmodifiableSortedSet(s: SortedSet): SortedSet
Returns an immutable set containing the specified object.
Returns an immutable list containing the specified object.
Returns an immutable map with the key and value pair.
Returns a read-only view of the collection.
Returns a read-only view of the list.
Returns a read-only view of the map.
Returns a read-only view of the set.
Returns a read-only view of the sorted map.
Returns a read-only view of the sorted set.
F
IGURE
21.7
The
Collections
class contains the static methods for creating singleton and read-only sets, lists, and maps.
an immutable list containing only a single item, and the
singletonMap(Object key,
Object value)
method for creating an immutable map containing only a single entry.
The
Collections
class also provides six static methods for returning
read-only views for
collections
:
unmodifiableCollection(Collection c)
,
unmodifiableList(List
list)
,
unmodifiableMap(Map m)
,
unmodifiableSet(Set set)
,
unmodifiableSortedMap(SortedMap m)
, and
unmodifiableSortedSet(Sorted
Set s)
. This type of view is like a reference to the actual collection. But you cannot modify
the collection through a read-only view. Attempting to modify a collection through a read-
only view will cause an
UnsupportedOperationException
.
read-only view
21.24
What is wrong in the following code?
✓
✓
Check
Point
Set<String> set = Collections.singleton(
"Chicago"
);
set.add(
"Dallas"
);
21.25
What happens when you run the following code?
List list = Collections.unmodifiableList(Arrays.asList(
"Chicago"
,
"Boston"
));
list.remove(
"Dallas"
);
K
EY
T
ERMS
hash map 813
hash set 798
linked hash map
set 798
read-only view
817
813
tree map
813
linked hash set
802
tree set
803
map
810
C
HAPTER
S
UMMARY
1.
A set stores nonduplicate elements. To allow duplicate elements to be stored in a collec-
tion, you need to use a list.
2.
A
map
stores key/value pairs. It provides a quick lookup for a value using a key.
3.
Three types of sets are supported:
HashSet
,
LinkedHashSet
, and
TreeSet
.
HashSet
stores elements in an unpredictable order.
LinkedHashSet
stores elements in the order
Search WWH ::
Custom Search