Implements several interfaces with conflict in signatures

Lasty, I tried to implement a hybrid structure in Java, something similar:

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 the methos signature of the Set interface and the Map interface in Java. I finally decided to implement only the Set interface and add the Map method without implementing this interface.

Do you see a more pleasant solution?

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

Have a set structure and you can effectively access a subset of the values ​​of this set that correspond to a given key value. At first I created a map and a set, but I tried to combine the two structures to optimize performance.

+3
source share
3 answers

, , . , , , ? , ? ? , ? :

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

Set as map,

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

.

+1

? Map Set [keySet()] (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet()). iteratior order, there LinkedHashMap TreeMap.

UPDATE: , , , , - SingleEntryMap put(K key, V value), , .

UPDATE: - ? ( , )

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;
    }
}
+3

I would say that something that is supposed to be used as a Map, and sometimes as a Set, should implement Map, since this can be considered as a set of keys or values, as well as a mapping between keys and values. To do this, use the methods Map.containsKey () and Map.containsValue ().

0
source

Source: https://habr.com/ru/post/1696941/


All Articles