两种扩展 Set 的边界不兼容

Incompatible bounds on two types extending Set

我不明白为什么这行不通。我有一个通用的 class Test<K,E extends Set> 接受类型 E 作为第二个参数,它至少是 Set.

我有另一个名为 Pair 的内部静态 class,它也采用第二种类型 F,它也至少是一个 Set

public class Test <K,E extends Set> {
    public static class Pair<L,F extends Set> {
        private L l;
        private F f;

        public Pair(L l, F f) {
            this.l = l;
            this.f = f;
        }
    }

    private Set<Pair<K,E>> pairs = new HashSet<>();

    private void test(K k){
        Set set = new HashSet<>();
        pairs.add(new Pair<>(k,set));
    }



}

但是,我无法将类型为 KSet 的对象添加到我的配对集中,我也不知道为什么。

错误日志:

Error:(26, 14) java: no suitable method found for add(test.o.Utils.Test.Pair<K,java.util.Set>)
    method java.util.Collection.add(test.o.Utils.Test.Pair<K,E>) is not applicable
      (argument mismatch; cannot infer type arguments for test.o.Utils.Test.Pair<>
          reason: inference variable F has incompatible bounds
            equality constraints: E
            lower bounds: java.util.Set)
    method java.util.Set.add(test.o.Utils.Test.Pair<K,E>) is not applicable
      (argument mismatch; cannot infer type arguments for test.o.Utils.Test.Pair<>
          reason: inference variable F has incompatible bounds
            equality constraints: E
            lower bounds: java.util.Set)

您是否期望其他人能够指定可用于测试的集合类型?如果您不是,则没有理由拥有第二个通用:

public class Test<K> {
    public static class Pair<L> {
        private L l;
        private Set f;

        public Pair(L l, Set f) {
            this.l = l;
            this.f = f;
        }
    }

    private Set<Pair<K, Set>> pairs = new HashSet<>();

    private void test(K k){
        Set set = new HashSet();
        pairs.add(new Pair<>(k,set));
   }
}

您可能想要指定集合中的内容。

public class Test<K, E> {
    public static class Pair<L, F> {
        private L l;
        private Set<F> fs;

        public Pair(L l, Set<F> fs) {
            this.l = l;
            this.fs = fs;
        }
    }

    private Set<Pair<K, E>> pairs = new HashSet<>();

    private void test(K k){
        Set<E> set = new HashSet<>();
        pairs.add(new Pair<>(k,set));
   }
}

不确定您要做什么,但您应该查看 Multimap。 Guava 有一个很好的实现。它允许将一个键与多个值(在一个集合内)相关联,这实际上就是您在这里所做的。