package priorityqueue.heap; import exceptions.InvalidEntryException; import position.Position; import priorityqueue.AdaptablePriorityQueue; import priorityqueue.Entry; import priorityqueue.MyEntry; import exceptions.InvalidKeyException; import java.util.Comparator; /** * Created with MONSTER. * User: xgiovio * Date: 11/05/2014 * Time: 14:55 */ public class HeapAdaptablePriorityQueue extends HeapPriorityQueue implements AdaptablePriorityQueue { public HeapAdaptablePriorityQueue() { super(); } public HeapAdaptablePriorityQueue(Comparator comp) { super(comp); } //override from parent class public Entry insert (K k, V v) throws InvalidKeyException { checkKey(k); LocationAwareEntry entry = new LocationAwareEntry(k,v); Position > z = heap.add(entry); entry.setLocation(z); upHeap(z); return entry; } protected void swap(Position> u,Position> v) { super.swap(u,v); getEntry(u).setLocation(u); getEntry(v).setLocation(v); } //end override from parent class public Entry remove(Entry entry) throws InvalidEntryException { LocationAwareEntry ee = checkEntry(entry); Position < Entry> p = ee.location(); if(size() == 1) return (Entry) heap.remove(); replaceEntry(p,(LocationAwareEntry)heap.remove()); upHeap(p); downHeap(p); ee.setLocation(null); return ee; } public K replaceKey(Entry entry, K k) throws InvalidEntryException,InvalidKeyException { checkKey(k); LocationAwareEntry ee = checkEntry(entry); K oldKey = ee.setKey(k); upHeap(ee.location()); downHeap(ee.location()); return oldKey; } public V replaceValue(Entry e, V value) throws InvalidEntryException { LocationAwareEntry ee = checkEntry(e); return ee.setValue(value); } //auxiliar protected Position< Entry> replaceEntry(Position> v, LocationAwareEntry e) { heap.replace(v,e); return e.setLocation(v); } protected LocationAwareEntry getEntry(Position >p) { return (LocationAwareEntry) p.element(); } protected LocationAwareEntry checkEntry(Entry e) throws InvalidEntryException { if(e == null || !(e instanceof LocationAwareEntry) || isEmpty() ) throw new InvalidEntryException("entrata non valida"); return (LocationAwareEntry) e; } // 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 + ")"; } } public String toString() { return super.toString(); } }