位置:org.springframework.util
�实现接口:java.util.List , java.io.Serializable
继承类:无
作用:根据需要自动填充列表元素

一、效果

  1. public void test1(){
  2. AutoPopulatingList<String> strList = new AutoPopulatingList<>(String.class);
  3. String s = strList.get(5); // 获取不到元素,则会根据给定索引自动填充集合
  4. strList.set(2,"test");
  5. for (String str : strList) {
  6. System.out.print(str + " "); // 输出:null null test null null
  7. }
  8. }

二、API

  1. // API委托实现的实际集合
  2. private final List<E> backingList;
  3. // 内部工厂类,用于根据需要创建新的List元素
  4. private final ElementFactory<E> elementFactory;
  5. // 工厂类接口,规定根据对象类型,基于反射原理返回元素对象(目前index无实际作用,应该为预留参数)
  6. public interface ElementFactory<E> {
  7. E createElement(int index) throws ElementInstantiationException;
  8. }
  9. /**
  10. 核心API:
  11. 在提供的索引处获取元素,如果该索引处没有元素,则创建该元素。
  12. */
  13. public E get(int index) {
  14. int backingListSize = this.backingList.size();
  15. E element = null;
  16. if (index < backingListSize) {
  17. element = this.backingList.get(index);
  18. if (element == null) {
  19. element = this.elementFactory.createElement(index);
  20. this.backingList.set(index, element);
  21. }
  22. }
  23. else {
  24. for (int x = backingListSize; x < index; x++) {
  25. this.backingList.add(null);
  26. }
  27. element = this.elementFactory.createElement(index);
  28. this.backingList.add(element);
  29. }
  30. return element;
  31. }

三、总结

AutoPopulatingList提供的API与List接口基本相同,不同点在于根据索引返回元素时会自动填充空位。
AutoPopulatingList不是线程安全的。要创建线程安全版本,可使用java.util.Collections.synchronizedList类。

四、补充