java - 实现几个签名冲突的接口(interface)

标签 java collections

最后,我尝试在 Java 中实现一个混合结构,看起来像这样:

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

其中HasKey是以下接口(interface):

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

不幸的是,Java 中的Set 接口(interface)和Map 接口(interface)的methos 签名之间存在一些冲突。我最终选择只实现 Set 接口(interface),并在不实现该接口(interface)的情况下添加 Map 方法。

你看到更好的解决方案了吗?

针对第一条评论,我的目标是:

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.

最佳答案

你想完成什么? Map 已经通过其 [keySet()]( http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet()) 方法将其键公开为 Set。如果您想要可靠的迭代顺序,则有 LinkedHashMapTreeMap

更新:如果你想确保一个值只被插入一次,你可以扩展我上面提到的类之一来创建类似 SingleEntryMap 的东西并覆盖 的实现put(K key, V value) 进行唯一性检查并在值已插入时抛出异常。

更新:这样的事情会奏效吗? (我没有打开我的编辑器,所以这可能无法编译)

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

关于java - 实现几个签名冲突的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70732/

相关文章:

c# - 如何创建无重复的ConcurrentQueue?

caching - 使用 redis 缓存管理器、redisTemplate 和多个序列化器进行缓存

java - 使用java流从集合集合中删除一些值

java - 追加字节

java - 使用 Spring Framework Cloud 时无法将 Artifact 从中央 Maven 存储库传输到中央 Maven 存储库

java - 如何在Intellij Idea中找到所有未使用的类?

java - POJO 类被序列化,没有读/写使用

java - 在 Java 中搜索集合

启用过滤器时 Hibernate 无法重新创建集合

java - 如何打造专业定制的Java Swing Gui?