package journal.tools; import java.util.AbstractList; import java.util.List; import java.util.Map; import java.util.HashMap; public class SparseList<E> extends AbstractList<E> implements List<E> { private Map<Integer, E> backing = new HashMap<Integer, E>(); private int size = 0; private final E defaultValue; public SparseList(E defaultValue) { this.defaultValue = defaultValue; } private void checkSize(int index) { if( index > size ) { size = index + 1; } } private E returnValue(E result) { return result == null ? defaultValue : result; } @Override public E get(int arg) { E result = backing.get(arg); return returnValue(result); } @Override public int size() { return size; } @Override public E set(int index, E element) { checkSize( index ); if( element == defaultValue ) { E result = backing.remove(index); return returnValue(result); } if( element == null ) throw new NullPointerException(); E result = backing.put( index, element ); return returnValue(result); } @Override public E remove(int index) { throw new UnsupportedOperationException("Not yet implemented"); } public static void main(String args[]) { SparseList<Integer> list = new SparseList<Integer>(0); list.set(1, 1); list.set(5, 5); list.set(17, 1); list.set(17, list.get(17) + 1); list.set(19, list.get(19) + 1); for( int index = 0; index < list.size(); index++ ) { System.out.println("" + index + " : " + list.get(index)); } } }
# | Change | User | Description | Committed | |
---|---|---|---|---|---|
#1 | 7527 | Sven Erik Knop |
JournalReader, now in its proper place. Documentation to follow. |