GrowthList - 成長するよリスト 2008/09/11

Javaです。
java.util.Listのインターフェイスに、indexを指定できるsetメソッドがあります。
これは、インデックスが範囲外の場合、IndexOutOfBoundsException 例外を発生するようになっています。

気分的には、サイズが足りない場合は、補間してセットできたらいいかなぁと思うことがあります。

そんなクラスどこかにないかなぁというわけで、さがすとapache.commons.collections.list.GrowthListというのがありました。
このクラスに用意されているsetはIndexOutOfBoundsExceptionを発生させません。

Collections - Home

それで、自分のニーズにあわないのは、補間される値がnullであること(まあそういうものだろうという気はします。)

そう思ってうろうろ散策していたら、org.apache.commons.collections.list.LazyListというものがあり、
decorateする際の指定の仕方によっては値がない場合に任意のオブジェクトを返すことができることがわかりました。

参考
2006-07-03 - a geek

次に、getするだけでサイズが大きくなる可能性がある....
それはそれで仕方がないか....

以下コード

import java.util.List;

import org.apache.commons.collections.functors.ConstantFactory;
import org.apache.commons.collections.list.GrowthList;
import org.apache.commons.collections.list.LazyList;

public class TestCollection {

public static void main(String[] args) {

List<String> list = LazyList.decorate(new GrowthList(), ConstantFactory
.getInstance("o_o!"));

list.set(8, "aaa");
System.out.println(list);
System.out.println(list.get(5));
System.out.println(list);
}

}


結果
[null, null, null, null, null, null, null, null, aaa]
o_o!
[null, null, null, null, null, o_o!, null, null, aaa]

: