Map.Entry 的泛型树集实现

Treeset Implementation of Map.Entry with Generic Types

我正在构建一个频率 table 实现,其中 hashmap table 元素是链式树集。 key/value对class提供了一个class定义如下:

public class CountablePair<F, S extends Comparable<? super S>> implements Comparable<S> {

我想创建一个新的 class EntryTreeSet 实现 Map.Entry,并在其中包含一个 Countable 对的树集。我当前的 class 声明代码、它的树集变量和构造函数如下:

public class EntryTreeSet<F,S> implements Map.Entry<F,S> {

private TreeSet<CountablePair<F,S>> tree;

public EntryTreeSet() {
    this.tree = new TreeSet<CountablePair<F,S>>();
}

但是,这会产生以下错误语句:

EntryTreeSet.java:19: error: type argument S#1 is not within bounds of type-variable S#2 private TreeSet> tree; ^ where S#1,S#2 are type-variables: S#1 extends Object declared in class EntryTreeSet S#2 extends Comparable declared in class CountablePair EntryTreeSet.java:22: error: type argument S#1 is not within bounds of type-variable S#2 this.tree = new TreeSet>(); ^ where S#1,S#2 are type-variables: S#1 extends Object declared in class EntryTreeSet S#2 extends Comparable declared in class CountablePair

我想知道如何正确地使我的树集包含 CountablePair class 的实例。

您的代码中唯一的问题似乎是 EntryTreeSet 声明中的 S 参数没有边界。这样的 class 声明编译正确:

public class EntryTreeSet<F, S extends Comparable<? super S>> 
                         implements Map.Entry<F, S> {

S 是原始类型,这就是编译错误出现的原因。 试试下面的代码。

public class EntryTreeSet<F,S extends Comparable<? super S>> implements Map.Entry<F,S>