I have a question regarding generic types. I have written my own iterator type and would like to return an empty iterator if there is nothing to iterate over.
The following code works,
@Override
public Iterator<MyType> iterator() {
final Iterator<MyType> iter = Collections.emptyIterator();
return count > 0 ? new MyIterator() : iter;
}
however, it does not work, if written in one line like this:
@Override
public Iterator<MyType> iterator() {
return count > 0 ? new MyIterator() : Collections.emptyIterator();
}
I get an error and have to cast the type to solve it:
@Override
public Iterator<MyType> iterator() {
return (Iterator<MyType>)(count > 0 ? new MyIterator() : Collections.emptyIterator());
}
This cast leads then to a unchecked warning, in the first example there is no warning.
When I move the cast to the inside, it does not work either:
@Override
public Iterator<MyType> iterator() {
return count > 0 ? new EdgeIterator() : (Iterator<MyType>) Collections.emptyIterator();
}
My question now is: why can't the compiler decide that the types are correct in the latter examples, but in the first. Why does the cast in variant 3 work, but not in the last one? The variants are all are basically the same in my impression.
If you want it to work, use this syntax :
return Collections.<MyType>emptyIterator();
This is how to give the generic to a static method.
If you call Collections.emptyIterator();
then it returns a Iterator<Object>
which is incompatible with your return type.
You also cannot cast because Iterator<MyType>
does not extends Iterator<Object>
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments