Iterator declaration <? extends E & Comparable <? super E >> iterator in java
Is it possible to declare the following in Java?
public class NewIterator<E extends Comparable<? super E>> implements Iterator<E> { NewIterator(Iterator<? extends E & Comparable<? super E>> iterator){ ... } I get an error
Multiple markers at this line - Incorrect number of arguments for type Iterator<E>; it cannot be parameterized with arguments <? extends E, Comparable<? super E>> - Syntax error on token ",", ; expected - Syntax error on token "&", , expected - Syntax error on token ")", ; expected Defining your class as
class NewIterator<E extends Comparable<? super E>> implements Iterator<E> { you say that E should implement Comparable<? super E> Comparable<? super E> .
Now in the constructor you will try to repeat this and allow subtypes of E.
NewIterator(Iterator<? extends E & Comparable<? super E>> iterator){ ... } If you just
public NewIterator(Iterator<? extends E> iterator) { } You should get what you want, because E already determines that it is a type that implements a comparable interface.
Example
class IntegerNumber {} class PositiveNumber extends IntegerNumber implements Comparable<IntegerNumber> {} class OddPositiveNumber extends PositiveNumber {} private NewIterator<PositiveNumber> newIterator; void foo() { Iterator<PositiveNumber> iterator = createIteratorFrom( new PositiveNumber(1), new OddPositiveNumber(7) ); this.newIterator = new NewIterator(iterator); } If you use PositiveNumber in NewIterator<E extends Comparable<? super E>> NewIterator<E extends Comparable<? super E>> , you can replace E with PositiveNumber . So your constructor accepts Iterator<? extends PositiveNumber> Iterator<? extends PositiveNumber> . Now you can create an iterator for any subclass of PositiveNumber , but since this class inherits from PositiveNumber , it must also inherit the Comparable<IntegerNumber> interface.