114 lines
2.5 KiB
Java
114 lines
2.5 KiB
Java
package map;
|
|
|
|
import position.NodePositionList;
|
|
import position.Position;
|
|
import position.PositionList;
|
|
import priorityqueue.Entry;
|
|
import priorityqueue.MyEntry;
|
|
|
|
import exceptions.InvalidKeyException;
|
|
import java.util.Iterator;
|
|
|
|
/**
|
|
* Created with MONSTER.
|
|
* User: xgiovio
|
|
* Date: 11/05/2014
|
|
* Time: 18:01
|
|
*/
|
|
public class ListMap<K,V> implements Map<K,V> {
|
|
|
|
private PositionList<Entry<K,V>> L;
|
|
|
|
public ListMap(){
|
|
L =new NodePositionList<Entry<K,V>>();
|
|
}
|
|
|
|
@Override
|
|
public int size() {
|
|
return L.size();
|
|
}
|
|
|
|
@Override
|
|
public boolean isEmpty() {
|
|
return (L.isEmpty());
|
|
}
|
|
|
|
|
|
|
|
|
|
public V put(K key, V value) throws InvalidKeyException {
|
|
checkKey(key);
|
|
for(Position<Entry<K,V>> p: L.positions()){
|
|
Entry<K,V> e= p.element();
|
|
if(e.getKey().equals(key)){
|
|
V v = e.getValue();
|
|
L.set(p, new MyEntry<K,V>(key,value));
|
|
return v;
|
|
} }
|
|
L.addLast(new MyEntry<K,V>(key,value));
|
|
return null;
|
|
}
|
|
|
|
public V get(K key) throws InvalidKeyException{
|
|
checkKey(key);
|
|
for(Position<Entry<K,V>> p: L.positions()){
|
|
Entry<K,V> e= p.element();
|
|
if(e.getKey().equals(key)) return e.getValue();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
|
|
public V remove(K key) throws InvalidKeyException {
|
|
checkKey(key);
|
|
for(Position<Entry<K,V>> p: L.positions()){
|
|
Entry<K,V> e= p.element();
|
|
if(e.getKey().equals(key)){
|
|
V v = e.getValue();
|
|
L.remove(p);
|
|
return v;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
@Override
|
|
public Iterable<K> keys() {
|
|
Iterator<Entry<K,V>> it = L.iterator();
|
|
NodePositionList<K> ret = new NodePositionList<K>();
|
|
for (;it.hasNext();){
|
|
ret.addLast(it.next().getKey());
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
@Override
|
|
public Iterable<V> values() {
|
|
Iterator<Entry<K,V>> it = L.iterator();
|
|
NodePositionList<V> ret = new NodePositionList<V>();
|
|
for (;it.hasNext();){
|
|
ret.addLast(it.next().getValue());
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
@Override
|
|
public Iterable<Entry<K, V>> entries() {
|
|
return L;
|
|
}
|
|
|
|
|
|
|
|
// auxiliar
|
|
protected void checkKey(K key) throws InvalidKeyException {
|
|
if (key == null )
|
|
throw new InvalidKeyException("Invalid key");
|
|
}
|
|
|
|
|
|
@Override
|
|
public String toString() {
|
|
return L.toString();
|
|
}
|
|
}
|