package dictionary; import exceptions.InvalidEntryException; import position.NodePositionList; import position.Position; import priorityqueue.Entry; import priorityqueue.MyEntry; import exceptions.InvalidKeyException; /** * Created with MONSTER. * User: xgiovio * Date: 11/05/2014 * Time: 19:04 */ public class LogFile implements Dictionary { NodePositionList> list = new NodePositionList>(); @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public Entry find(K key) throws InvalidKeyException { checkKey(key); for(Position> p: list.positions()){ Entry e= p.element(); if(e.getKey().equals(key)){ return e; } } return null; } @Override public Iterable> findAll(K key) throws InvalidKeyException { checkKey(key); NodePositionList> to_return = new NodePositionList>(); for(Position> p: list.positions()){ Entry e= p.element(); if(e.getKey().equals(key)){ to_return.addLast(e); } } return to_return; } @Override public Entry insert(K key, V value) throws InvalidKeyException { checkKey(key); LocationAwareEntry t = new LocationAwareEntry(key,value); list.addLast(t); t.setLocation(list.last()); return t; } protected Entry insert(Entry in_e) throws InvalidKeyException { //in_e not used because used internally LocationAwareEntry t = (LocationAwareEntry)in_e; list.addLast(t); t.setLocation(list.last()); return t; } @Override public Entry remove(Entry e) throws InvalidEntryException { LocationAwareEntry t = checkEntry(e); list.remove(t.location()); t.setLocation(null); return t; } @Override public Iterable> entries() { return list; } //aux protected void checkKey(K key) throws InvalidKeyException { if (key == null ) throw new InvalidKeyException("Invalid key"); } // inner class protected static class LocationAwareEntry extends MyEntry { protected Position> loc = null; public LocationAwareEntry(K k, V v) { super(k, v); } public LocationAwareEntry(K k, V v, Position pos) { super(k, v); loc = pos; } protected Position < Entry> location() { return loc; } protected Position < Entry >setLocation(Position< Entry> pos) { Position > oldPosition = location(); loc = pos; return oldPosition; } protected K setKey(K k) { K oldKey = getKey(); key = k; return oldKey; } protected V setValue(V v) { V oldValue = getValue(); value = v; return oldValue; } public String toString() { return "(" + key + "," + value + ")"; } } protected LocationAwareEntry checkEntry(Entry e) throws InvalidEntryException { if(e == null || !(e instanceof LocationAwareEntry) || isEmpty() ) throw new InvalidEntryException("entrata non valida"); return (LocationAwareEntry) e; } }