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.
Hashtable has method contains, but
Map has
containsValue parallels
containsKey.
4. Implementations
| Interfaces | Hash table Implementations | Resizable array Implementations | Tree Implementations | Linked list Implementations | Hash table + Linked list Implementations |
|---|---|---|---|---|---|
Set | HashSet | TreeSet | LinkedHashSet | ||
List | ArrayList | LinkedList | |||
Queue | |||||
Map | HashMap | TreeMap | LinkedHashMap |
Queue implementation include LinkedList and PriorityQueue.
5. Convenience Implementations
b. Immutable Multiple-Copy List
c. Immutable Singleton Set
d.Empty Set, List, and Map Constants
The Collections.emptySet, Collections.emptyList, and Collections.emptyMap.
本文探讨了Java集合框架中的Iterator使用技巧、批量操作、Map接口与Hashtable的区别及实现方式,包括如何高效迭代和过滤元素,以及Map接口提供的集合视图、迭代和删除操作优势。同时介绍了各种通用和便利实现的集合类,如List、Set、Map及其具体实例,为开发者提供深入理解Java集合框架的实用指南。
264

被折叠的 条评论
为什么被折叠?



