Question

Lasty, I tried to implements an hybrid structure in Java, something that looks like:

public class MapOfSet<K, V extends HasKey<K>> implements Set<V>, Map<K, Set<V>>

Where HasKey is the following interface:

public interface HasKey<K> {
    public K getKey();
}

Unfortunately, there are some conflicts between methos signature of the Set interface and the Map interface in Java. I've finally chosen to implements only the Set interface and to add the Map method without implementing this interface.

Do you see a nicer solution?

In response to the first comments, here is my goal:

Have a set structure and be able to efficiently access to a subset of values of this set, corresponding to a given key value. At the beginning I instantiated a map and a set, but I tried to joined the two structures to optimize performances.

Was it helpful?

Solution

Perhaps you could add more information which operations do you really want. I guess you want to create a set which automatically groups their elements by a key, right? The question is which operations do you want to be able to have? How are elements added to the Set? Can elements be deleted by removing them from a grouped view? My proposal would be an interface like that:

public interface GroupedSet<K, V extends HasKey<K>> extends Set<V>{
    Set<V> havingKey(K k);
}

If you want to be able to use the Set as map you can add another method

Map<K,Set<V>> asMap();

That avoids the use of multiple interface inheritance and the resulting problems.

OTHER TIPS

What are you trying to accomplish? Map already exposes its keys as a Set via its [keySet()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet()) method. If you want a reliable iteratior order, there's LinkedHashMap and TreeMap.

UPDATE: If you want to ensure that a value has only been inserted once, you can extend one of the classes I mentioned above to create something like a SingleEntryMap and override the implementation of put(K key, V value) to do a uniqueness check and throw an Exception when the value has already been inserted.

UPDATE: Will something like this work? (I don't have my editor up, so this may not compile)

public final class KeyedSets<K, V> implements Map<K,Set<V>> {
    private final Map<K, Set<V>> internalMap = new TreeMap<K, Set<V>>;
    // delegate methods go here
    public Set<V> getSortedSuperset() {
        final Set<V> superset = new TreeSet<V>();
        for (final Map.Entry<K, V> entry : internalMap.entrySet()) {
            superset.addAll(entry.getValue());
        }
        return superset;
    }
}

I would say that something that is meant to be sometimes used as a Map and sometimes as a Set should implement Map, since that can be viewed as a set of keys or values as well as a mapping between keys and values. That is what the Map.containsKey() and Map.containsValue() methods are for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top