Why Java Collection Framework doesn't contain Tree and Graph

卢声远 Shengyuan Lu picture 卢声远 Shengyuan Lu · Feb 12, 2011 · Viewed 32k times · Source

I am familiar with Java Collection Framework which contains basic interfaces: Collection and Map. I am wondering why the Framework doesn't contain structures as Tree and Graph which are basic collections. Both can be regarded as sub types of Collection.

By the way, I know TreeSet is implemented by Red-Black Tree underlying. However, the TreeSet is not a Tree but a Set, so there's no real Tree in the framework.

Answer

aioobe picture aioobe · Feb 12, 2011

I am wondering why the Framework doesn't contain structures as Tree and Graph which are basic collections. Both can be regarded as sub types of Collection.

This is a good question. I think it simply boils down to scoping. The core features that Collections API provides classes for are:

  • iteration order: Lists and sorted maps have specified iteration order, most sets don't.

  • duplicates: Lists allow duplicates, sets do not

  • index: List values are indexed by integers, map values are indexed by other objects.

This gets us very far and I assume Joshua Bloch et al argued that more feature rich collections (graphs and trees which require internal relationship between elements, sets with multiplicity, bi-directional maps, ...) can be implemented on top of these three core features, and are thus better off in libraries.