日期:2014-05-20 浏览次数:20930 次
1. Use Iterator instead of the for-each construct when you need to:
a. Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
b. Iterate over multiple collections in parallel.
for (Iterator<String> i = c.iterator(); i.hasNext(); )
if (i.next().length() == 4)
i.remove();
?
?2. bulk operation
a. removeAll()
c.removeAll(Collections.singleton(e));
More specifically, suppose you want to remove all of the null elements from a Collection.
c.removeAll(Collections.singleton(null));
?
3. Map Interface
a.?Comparison to Hashtable?
Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface, as discussed later in this section. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; Hashtable did not.containsKey. ?
4. Implementations
?
Set |
HashSet |
? | TreeSet |
? | LinkedHashSet |
List |
? | ArrayList |
? | LinkedList |
? |
Queue |
? | ? | ? | ? | ? |
Map |
HashMap |
? | TreeMap |
? | LinkedHashMap |
?
Queue implementation include LinkedList?and PriorityQueue.
?
5. Convenience Implementations
a. Arrays.asList
b. Immutable Multiple-Copy List
??? Collections.nCopies
c. Immutable Singleton Set
??? Collections.singleton
d.Empty Set, List, and Map Constants
??? The Collections.emptySet, Collections.emptyList, and Collections.emptyMap.