Wednesday, November 28, 2012

apache commons --- collections

这主要是弥补 SDK 里面容器的一些不足(好像 STL 的容器类用起来就比较完整),当然由于 Java 的设计问题,接口实在是太封闭,使用 adaptor 又显得累赘,collections 本质上是提供了另外一些容器和接口,既没有扩展原先的那些容器,也似乎没提供什么 adaptor。我们先看看这个 package 里面(org.apache.commons3.collections)有些什么:
  • Bag/SortedBag 简单的说就是个 Map,能够用来计数,支持 add/remove/getCount 这些操作,SortedBag 支持 first/last,返回的是数目最少和最多的,对应的一些实现放在 org.apache.commons.collections.bag 里面,包括 HashBag/TreeBag(明显对应 HashMap 和 TreeMap 的实现),几个 decorator 包括 PredicatedBag(要求满足predicate 的操作),SynchronizedBag(实现了 synchronization,可用在多线程中),TransformedBag(插入时会先做 Transform)。它们也都是 Iterable 和 Collection。
  • BidiMap/SortedBidiMap,简单的说就和 boost.bimap 类似,提供从 key 到 value 的映射也提供反方向的,接口与 Map 类似,额外有 getKey、getInverseBidiMap(将 key/value 反过来)、removeValue 等。实现在 org.apache.commons3.collections.bidimap 中,有 DualHashBidiMap/DualTreeHashBidiMap 等。
  • IterableMap 要求提供 mapIterator 方法获得 MapIterator 对象用于遍历
  • Buffer 要求提供 get 和 remove,适合作为队列等实现的接口,实现在 org.apache.commons3.collections.buffer 中
另外有不少辅助的 interface 有兴趣可以看看这里。下面是几个 snippet
IterableMap map = new HashedMap();
MapIterator it = map.mapIterator();
while (it.hasNext()) {
  Object key = it.next();
  Object value = it.getValue();
  
  it.setValue(newValue);
}

BidiMap bidi = new TreeBidiMap();
bidi.put("SIX", "6");
bidi.get("SIX");  // returns "6"
bidi.getKey("6");  // returns "SIX"
bidi.removeValue("6");  // removes the mapping
BidiMap inverse = bidi.inverseBidiMap();  // returns a map with keys and values swapped

Buffer buffer = new UnboundedFifoBuffer();
buffer.add("ONE");
buffer.add("TWO");
buffer.add("THREE");
buffer.remove();  // removes and returns the next in order, "ONE" as this is a FIFO
buffer.remove();  // removes and returns the next in order, "TWO" as this is a FIFO
似乎不支持 generics?另外还有个 LRUMap 可能有点用...

apache commons --- attributes

这是一个比较常用的 Java 程序集合,它包括很多组建,比如前面所说的 logging 等。这里是其中的 attributes。不过这个库说实在的没太看明白,据说是1.5 之前由于 javadoc 不是很好用自己弄出来的一套给一些元素(类、方法、参数等)进行属性标识的。现在应该只在很老的 code 里面看见了吧