diff --git a/src/it/algoritmi/adt/Entry.java b/src/it/algoritmi/adt/Entry.java new file mode 100644 index 0000000..cd5c6cb --- /dev/null +++ b/src/it/algoritmi/adt/Entry.java @@ -0,0 +1,16 @@ +package it.algoritmi.adt; + +/** + * Interfaccia per una coppia chiave-valore + * @author fabio + * + * @param + * @param + */ +public interface Entry { + + K getKey(); + + V getValue(); + +} diff --git a/src/it/algoritmi/adt/PriorityQueue.java b/src/it/algoritmi/adt/PriorityQueue.java new file mode 100644 index 0000000..c712bda --- /dev/null +++ b/src/it/algoritmi/adt/PriorityQueue.java @@ -0,0 +1,23 @@ +package it.algoritmi.adt; + +/** + * Interfaccia per l' ADT coda prioritaria. + * + * @author fabio + * + * @param + * @param + */ +public interface PriorityQueue, V> { + + int size(); + + boolean isEmpty(); + + Entry insert(K key, V value) throws IllegalArgumentException; + + Entry min(); + + Entry removeMin(); + +} diff --git a/src/it/algoritmi/adt/queue/AbstractPriorityQueue.java b/src/it/algoritmi/adt/queue/AbstractPriorityQueue.java new file mode 100644 index 0000000..cc604d5 --- /dev/null +++ b/src/it/algoritmi/adt/queue/AbstractPriorityQueue.java @@ -0,0 +1,73 @@ +package it.algoritmi.adt.queue; + +import java.util.Comparator; + +import it.algoritmi.adt.Entry; +import it.algoritmi.adt.PriorityQueue; + +public abstract class AbstractPriorityQueue, V> implements PriorityQueue { + + //--------------------------- classe PQEntry annidata -------------------------------- + protected static class PQEntry, V> implements Entry { + private K key; + private V value; + + public PQEntry(K key, V value) { + this.key = key; + this.value = value; + } + + @Override + public K getKey() { + return key; + } + + @Override + public V getValue() { + return value; + } + + public void setKey(K key) { + this.key = key; + } + + public void setValue(V value) { + this.value = value; + } + } + //-------- fine della classe annidata ------------------------ + + /** Il comparatore che definisce l'ordine tra le chiavi della coda prioritaria */ + private Comparator comparator; + + /** Crea una coda prioritaria vuota che usa il comparatore fornito. */ + protected AbstractPriorityQueue(Comparator comparator) { + this.comparator = comparator; + } + + /** Crea una coda prioritaria vuota che usa l'ordine naturale tra le chiavi */ + protected AbstractPriorityQueue() { + this((o1, o2) -> o1.compareTo(o2)); + } + + /** Metodo per confrontare due entità in base alle loro chiavi. */ + protected int compare(Entry a, Entry b) { + return comparator.compare(a.getKey(), b.getKey()); + } + + /** Determina se la chiave è valida. */ + protected boolean checkKey(K key) { + try { + return (comparator.compare(key, key)) == 0; + } catch (ClassCastException e) { + throw new IllegalArgumentException("Incompatible key"); + } + } + + /** Verifica se la coda prioritaria è vuota. */ + @Override + public boolean isEmpty() { + return size() == 0; + } + +}