Aggiunto interfacce per classi astratte per implementazione priority queue

This commit is contained in:
Fabio Scotto di Santolo
2018-03-15 21:13:07 +01:00
parent 1b7cfc0bcc
commit 481d81d4bd
3 changed files with 112 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
package it.algoritmi.adt;
/**
* Interfaccia per una coppia chiave-valore
* @author fabio
*
* @param <K>
* @param <V>
*/
public interface Entry<K, V> {
K getKey();
V getValue();
}

View File

@@ -0,0 +1,23 @@
package it.algoritmi.adt;
/**
* Interfaccia per l' ADT coda prioritaria.
*
* @author fabio
*
* @param <K>
* @param <V>
*/
public interface PriorityQueue<K extends Comparable<K>, V> {
int size();
boolean isEmpty();
Entry<K, V> insert(K key, V value) throws IllegalArgumentException;
Entry<K, V> min();
Entry<K, V> removeMin();
}

View File

@@ -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<K extends Comparable<K>, V> implements PriorityQueue<K, V> {
//--------------------------- classe PQEntry annidata --------------------------------
protected static class PQEntry<K extends Comparable<K>, V> implements Entry<K, V> {
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<K> comparator;
/** Crea una coda prioritaria vuota che usa il comparatore fornito. */
protected AbstractPriorityQueue(Comparator<K> 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<K, V> a, Entry<K, V> 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;
}
}