扩展Set的两个类型上的边界不兼容



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

我有另一个内部静态类Pair,它也采用第二种类型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)

您是否希望其他人能够指定可与Test一起使用的集合类型?如果你没有,就没有理由拥有第二个通用:

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有一个非常好的实现。它允许将一个键与多个值(在一个集合内)相关联,这基本上就是您在这里所做的。

最新更新