java集合享元的解决方案
为了从AbstractList创建只读的的List,必须实现get()和size()
package SourceCode;
import java.util.AbstractList;
public class CountingIntegerList extends AbstractList<Integer>{
private int size;
public CountingIntegerList(int size){
this.size = size;
}
public Integer get(int index){
return Integer.valueOf(index);
}
public int size(){return size;}
public static void main(String[] args) {
System.out.println(new CountingIntegerList(10));
}
}
执行结果:
当寻找List中的值时,get()将产生它,因此这个List实际上并不必组装。
剖析源码
查看AbstractList源码看其迭代器(iterator)的实现
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>
这里使用到get()和size()获得List对象的存储值,获得的迭代器就可以读List中的值了
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
配合AbstractCollection中对toString()来打印出List中所有的值.
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}