Java容器详解
Collection接口
List
- ArrayList:数组实现,查询快,增删慢
- LinkedList:链表实现,增删快,查询慢
- Vector:同步ArrayList
1 2 3 4
| List<String> list = new ArrayList<>(); list.add("a"); list.get(0); list.remove(0);
|
Set
- HashSet:哈希表,无序唯一
- LinkedHashSet:保持插入顺序
- TreeSet:红黑树,有序唯一
1 2
| Set<String> set = new HashSet<>(); set.add("a");
|
Queue
- LinkedList实现了Queue
- PriorityQueue:优先级队列
- BlockingQueue:阻塞队列
Map接口
- HashMap:JDK1.8后用红黑树
- LinkedHashMap:保持插入顺序
- TreeMap:红黑树,有序
- Hashtable:同步
1 2 3 4
| Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.get("a"); map.containsKey("a");
|
迭代器
1 2 3 4 5 6 7
| Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); }
for (String s : list) {}
|
总结
Java容器是日常开发中最常用的类,需要根据场景选择合适的实现。