I implemented a unique map. It's a hashmap which is bi-directional, where not only keys are unique but values too.
public interface UniqueMap<K,V>{
V uniquePut(K key, V value);
UniqueMap<V,K> inverse();
}
This is a possible implementation:
public class SimpleUniqueMap<K,V> implements UniqueMap<K,V>, Iterable<K>{
public HashMap<K,V> uniqueMap = new HashMap<K,V>();
class EnumSimpleUniqueMap implements Iterator<K>{
int count = uniqueMap.size();
public boolean hasNext(){
return count > 0;
}
public K next(){
if(count == 0){
throw new NoSuchElementException();
}else{
count--;
//...
}
}
public void remove(){
throw new UnsupportedOperationException();
}
}
public Iterator<V> iterator(){
return new EnumSimpleUniqueMap();
}
public V uniquePut(K key, V value){
return null;
}
public UniqueMap<V,K> inverse(){
return null;
}
}
As you can see I already tried to implement an iterator for my unique map. But from a hashmap values are not accessed by position but by key. So usually I would take the counter and access values but in this case it is not possibe.
Actually it would be enough to iterate over the keys and retrieve them one by another. How can I do that? Is there a way to retrieve some kind of entry object containing both key and value?
I know that I can retrieve the iterator from an map object but this is not an option for me.