1. Collection接口
集合框架定义了几个接口。集合框架的类和接口都在 java.util 包内。如下提供了每个接口的概览:
SN | 接口描述 |
---|---|
1 | Collection 接口 这让你可以使用对象组;它是集合层次阶段的顶端 |
2 | List 接口 它继承了 Collection 并且 List 的一个实例存储了元素的一个有序集合 |
3 | Set 它继承了 Collection 来处理集,它必须含有特殊的元素 |
4 | SortedSet 它继承了 Set 来处理 排序的 set |
5 | Map 它将独特的键和值匹配 |
6 | Map Entry 这描述了映射中的一个元素(一个键值对)。它是 Map 的一个内部类。使用迭代器时要用到这个。 |
7 | SortedMap 它继承了 Map 因此键按升序保持 |
8 | Enumeration 它是旧有的接口并定义了你可以在对象的集合中列举(一次获得一个)元素的方法。这个旧有的接口被迭代器取代了。 |
2. Collection类
Java提供了一系列的实现了集合接口的标准集合类。一些类提供了完全的能被直接使用的实现;其他就是抽象类,提供的被用来作为创建具体集合的实现。
SN | 类描述 |
---|---|
1 | AbstractCollection 实现大部分的 Collection 接口 |
2 | AbstractList 继承 AbstractCollection 并且实现大部分 List 接口 |
3 | AbstractSequentialList 通过一个使用有序的而不是随机访问它的元素的集合继承 AbstractList |
4 | LinkedList 通过继承 AbstractSequentialList 实现一个链表 |
5 | ArrayList 通过继承 AbstractList 实现一个动态数组 |
6 | AbstractSet 继承 AbstractCollection 并实现大部分的 Set 接口 |
7 | HashSet 用一个哈希表继承 AbstractSet |
8 | LinkedHashSet 继承 HashSet 来允许插入顺序迭代 |
9 | TreeSet 实现在树中存储的一个集。继承 AbstractSet |
10 | AbstractMap 实现大部分的 Map 接口 |
11 | HashMap 用一个哈希表继承 AbstractMap |
12 | TreeMap 用一棵树继承 AbstractMap |
13 | WeakHashMap 用一个使用弱键的哈希表来继承 AbstractMap |
14 | LinkedHashMap 继承 AbstractMap 来允许插入顺序迭代 |
15 | IdentityHashMap 继承 AbstractMap 类并且当比较文档时平等使用参考 |
3. 其它集合类
还有一些java.util定义的旧有的类: Vector, Stack, Hashtable, BitSet等。
4. 如何使用迭代器Iterator
- 不使用迭代器的删除问题
//常规方法一
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","a", "b","c", "d"));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals("a")) {
list.remove(i);
}
}
System.out.println(list);
}
//输出:[a, b, c, d]与预期不一致
//常规方法二
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","b","c","d"));
for(String s:list){
if(s.equals("a")){
list.remove(s);
}
}
//它会抛出一个ConcurrentModificationException异常
- 使用迭代器的正解
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","b","c","d"));
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
String s = iter.next();
if(s.equals("a")){
iter.remove();
}
}
- Map使用迭代器(需要转为EntrySet)
//构建Map
Map<String, String> source = new HashMap<String, String>();
for (int i = 0; i < 10; i++) {
source.put("key" + i, "value" + i);
}
//使用迭代器
Iterator<Map.Entry<String, String>> iterator = source.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (entry.getKey().contains("1")) {
iterator.remove();
}
}
System.out.println(source);
}