Reputation: 1689
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()). So I define a small Pair class:
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:
// 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?
Upvotes: 1
Views: 279
Reputation: 7889
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> {
// ...
}
Upvotes: 1
Reputation: 178253
The generic type parameter Pair<T>
is not valid; you just need to declare <T>
and use it when implementing the interface.
// Just <T> here; Added missing (2nd) '>'
class PairStream<T> implements Stream<Pair<T>> {
public Pair<T> get() { /* ... */ }
}
Upvotes: 5