简体   繁体   English

Java嵌套的通用类,只有一个类型参数

[英]Java nested generic class with only one type parameter

I'm working on a project that has a generic stream interface that provides values of a type: 我正在一个具有通用流接口的项目中,该接口提供一种类型的值:

interface Stream<T> {
  T get();  // returns the next value in the stream
}

I have one implementation that provides single values simply from a file or whatever. 我有一个实现仅从文件或其他任何内容提供单个值的实现。 It looks like this: 看起来像这样:

class SimpleStream<T> implements Stream<T> {
  // ...
}

I would also like to have another implementation that provides pairs of values (say, to provide the next two values for each call to get()). 我还希望有一个提供成对值的实现(例如,为每个对get()的调用提供下两个值)。 So I define a small Pair class: 所以我定义了一个小的Pair类:

class Pair<T> {
  public final T first, second;

  public Pair(T first, T second) {
    this.first = first; this.second = second;
}

and now I would like to define a second implementation of the Stream interface that only works with Pair classes, like this: 现在,我想定义仅适用于Pair类的Stream接口的第二种实现,如下所示:

// Doesn't compile
class PairStream<Pair<T>> implements Stream<Pair<T>> {
  // ...
}

This does not compile, however. 但是,这不会编译。

I could do this: 我可以这样做:

class PairStream<U extends Pair<T>, T> implements Stream<U> {
  // ...
}

but is there any more elegant way? 但是还有什么更优雅的方法吗? Is this the "right" way to do this? 这是这样做的“正确”方法吗?

The generic type parameter Pair<T> is not valid; 通用类型参数Pair<T>无效; you just need to declare <T> and use it when implementing the interface. 您只需要声明<T>并在实现接口时使用它。

//         Just <T> here;          Added missing (2nd) '>'
class PairStream<T> implements Stream<Pair<T>> {
    public Pair<T> get() { /* ... */ }
}

All you really need is 您真正需要的是

class PairStream<T> implements Stream<Pair<T>> {
  // ...
}

This might work too: 这也可能起作用:

class PairStream<U extends Pair<T>> implements Stream<U> {
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM