这是Java泛型中禁止的吗?

时间:2011-06-24 21:43:52

标签: java generics

class Collator<S extends Stream<E extends Comparable<E>>> {
    S s;
    E e;

    public <S> Collator(List<S> streams){
        s = streams.get(0);
        e = s.read();
    }

    public <E> E next(){
        return e;
    }
}

interface Stream<E extends Comparable<E>>{
    public E read();
}

class Record implements Comparable<Record>{
    public Integer time;

    public int compareTo(Record r){
        return this.time.compareTo(r.time);
    }
}

特别是第一行:

  class Collator<S extends Stream<E extends Comparable<E>>>

我希望说:

  

定义一个适用于条目流的整理器,其中每个条目实现可比较。

3 个答案:

答案 0 :(得分:4)

你错过了通用参数

class Collator<S extends Stream<E>,E extends Comparable<E>> {
    S s;
    E e;

    public Collator(List<S> streams){
        s = streams.get(0);
        e = s.read();
    }

    public E next(){
        return e;
    }
}

interface Stream<E extends Comparable<E>>{
    public E read();
}

class Record implements Comparable<Record>{
    public Integer time;

    public int compareTo(Record r){
        return this.time.compareTo(r.time);
    }
}

这个编译

特别是行class Collator<S extends Stream<E>,E extends Comparable<E>>它意味着一个Collat​​or工作于一个S,它是E和E的流,实现了Comparable

答案 1 :(得分:2)

一些玻璃球猜测,因为你没有显示你的错误信息:

您的构造函数和方法声明了新类型参数<E><S>,它们会影响类的类型参数。删除它们。

然后,E也应该是您班级的类型参数。

class Collator<E extends Comparable<E>, S extends Stream<E>> {
    S s;
    E e;

    public Collator(List<S> streams){
        s = streams.get(0);
        e = s.read();
    }

    public E next(){
        return e;
    }
}

interface Stream<E extends Comparable<E>>{
    public E read();
}

class Record implements Comparable<Record>{
    public Integer time;

    public int compareTo(Record r){
        return this.time.compareTo(r.time);
    }
}

答案 2 :(得分:0)

问题是E extends Comparable

定义一个在条目流上工作的整理器,其中每个条目实现与给定类型相当:

public class Collator<T,E extends Comparable<T>, S extends Stream<E>>