位置:org.springframework.util
�实现接口:java.util.List
继承类:无
作用:根据需要自动填充列表元素
一、效果
public void test1(){
AutoPopulatingList<String> strList = new AutoPopulatingList<>(String.class);
String s = strList.get(5); // 获取不到元素,则会根据给定索引自动填充集合
strList.set(2,"test");
for (String str : strList) {
System.out.print(str + " "); // 输出:null null test null null
}
}
二、API
// API委托实现的实际集合
private final List<E> backingList;
// 内部工厂类,用于根据需要创建新的List元素
private final ElementFactory<E> elementFactory;
// 工厂类接口,规定根据对象类型,基于反射原理返回元素对象(目前index无实际作用,应该为预留参数)
public interface ElementFactory<E> {
E createElement(int index) throws ElementInstantiationException;
}
/**
核心API:
在提供的索引处获取元素,如果该索引处没有元素,则创建该元素。
*/
public E get(int index) {
int backingListSize = this.backingList.size();
E element = null;
if (index < backingListSize) {
element = this.backingList.get(index);
if (element == null) {
element = this.elementFactory.createElement(index);
this.backingList.set(index, element);
}
}
else {
for (int x = backingListSize; x < index; x++) {
this.backingList.add(null);
}
element = this.elementFactory.createElement(index);
this.backingList.add(element);
}
return element;
}
三、总结
AutoPopulatingList提供的API与List接口基本相同,不同点在于根据索引返回元素时会自动填充空位。
AutoPopulatingList不是线程安全的。要创建线程安全版本,可使用java.util.Collections.synchronizedList类。
四、补充
无