总结:Java Collection Framework

(下面的讨论都是以JDK 1.6为准)
Java的发展历史很长了,而且很多社区贡献,不像.Net是MS一家在设计,反映在类库里面主要就是两个结果:
1、一直不断完善,啥都有,而且基本是实际使用中适合Java的best practice。
2、10多年一层一层磊上去的包、接口、实现,有些地方给人挺乱的感觉。

幸好SUN的The Collections Framework里面说得很详细,不然一开始肯定找不到北。照Overview里面的分类,把Java的集合框架分成11块:

Collection Interfaces - Represent different types of collections, such as sets, lists and maps. These interfaces form the basis of the framework.
General-purpose Implementations - Primary implementations of the collection interfaces.
Legacy Implementations - The collection classes from earlier releases, Vector and Hashtable, have been retrofitted to implement the collection interfaces.
Special-purpose Implementations - Implementations designed for use in special situations. These implementations display nonstandard performance characteristics, usage restrictions, or behavior.
Concurrent Implementations - Implementations designed for highly concurrent use.
Wrapper Implementations - Add functionality, such as synchronization, to other implementations.
Convenience Implementations - High-performance "mini-implementations" of the collection interfaces.
Abstract Implementations - Partial implementations of the collection interfaces to facilitate custom implementations.
Algorithms - Static methods that perform useful functions on collections, such as sorting a list.
Infrastructure - Interfaces that provide essential support for the collection interfaces.
Array Utilities - Utility functions for arrays of primitives and reference objects. Not, strictly speaking, a part of the Collections Framework, this functionality was added to the Java platform at the same time and relies on some of the same infrastructure.


平时用到的主要是General-purpose Impl那部分: 

 

Implementations

Hash Table

Resizable Array

Balanced Tree

Linked List

Hash Table + Linked List

Interfaces

Set

HashSet

 

TreeSet

 

LinkedHashSet

List

 

ArrayList

 

LinkedList

 

Deque

 

ArrayDeque

 

LinkedList

 

Map

HashMap

 

TreeMap

 

LinkedHashMap


主要的接口关系是这样的(注意Map没extends Collection):


另外有些地方比如老的代码会出现比较多1.1的Vector和HashTable,可以看做synchronized版的ArrayList和HashMap。
大家的声明长这样:

Java General-purpose Collections,点击加号展开!


Set其实都是Map<Key, Object>的封装,RB树、Hash系列,相关:Comparable接口或comparator.compare()、Object.hashCode()和Object.equals()。
有个好玩的地方是SUN的实现里面Object.hashCode()是返回对象的地址。

其中LinkedHashSet照理说是用HashSet加上LinkedList实现照插入顺序迭代,不过我看Java6带的LinkedHashSet.java源代码就那么短几行,没看出来哪有LinkedList。。
还有就是LinkedHashMap没实现Serializable,哪位高人指点下为什么?(暂时推测和它可以用来实现Cache有关)

PriorityQueue就是堆的数组实现。不过C++里面是用一个vector,Java里面的自己管理数组的增长。

最后,API Outline多多熟悉,那些Wrapper、Special-purpose的和Concurrent的集合类在需要的时候就用,毕竟类库里面的一般比自己实现的好。


Reference:
http://java.sun.com/javase/6/docs/technotes/guides/collections/index.html

posted @ 2008-06-28 22:00  VeryDxZ  阅读(791)  评论(0编辑  收藏  举报