E
Eric Sosman
In the old days, before generics, I wrote
private SortedSet onhand;
Iterator getInventoryIterator() {
return (onhand == null ? Collections.EMPTY_SET ? onhand)
.iterator();
}
.... the idea being to create the SortedSet only if there are
actually some Inventory objects to store in it, and to return
a suitable Iterator whether or not the SortedSet exists.
Now, in an effort to leave prehistory behind me and adopt
generics with all their benefits, I change the SortedSet to a
SortedSet<Inventory> and change the return type of the method
to Iterator<Inventory> -- but how do I rewrite the guts of the
method to get the compiler to understand that all is well? The
problem seems to be that Collections.EMPTY_SET.iterator() returns
an Iterator<Object>, and the compiler complains when I try to
return this in place of the desired Iterator<Inventory>. I've
tried a few variations, but have only succeeded in moving the
warning message around, not in eliminating it:
return (onhand == null
? (Set<Inventory>)Collections.EMPTY_SET : onhand)
.iterator();
return (Iterator<Inventory>)
(onhand == null ? Collections.EMPTY_SET ? onhand)
.iterator();
This seems like a lot of trouble to take over the empty set,
but there ought to be *some* clean way to do it. Ideas?
private SortedSet onhand;
Iterator getInventoryIterator() {
return (onhand == null ? Collections.EMPTY_SET ? onhand)
.iterator();
}
.... the idea being to create the SortedSet only if there are
actually some Inventory objects to store in it, and to return
a suitable Iterator whether or not the SortedSet exists.
Now, in an effort to leave prehistory behind me and adopt
generics with all their benefits, I change the SortedSet to a
SortedSet<Inventory> and change the return type of the method
to Iterator<Inventory> -- but how do I rewrite the guts of the
method to get the compiler to understand that all is well? The
problem seems to be that Collections.EMPTY_SET.iterator() returns
an Iterator<Object>, and the compiler complains when I try to
return this in place of the desired Iterator<Inventory>. I've
tried a few variations, but have only succeeded in moving the
warning message around, not in eliminating it:
return (onhand == null
? (Set<Inventory>)Collections.EMPTY_SET : onhand)
.iterator();
return (Iterator<Inventory>)
(onhand == null ? Collections.EMPTY_SET ? onhand)
.iterator();
This seems like a lot of trouble to take over the empty set,
but there ought to be *some* clean way to do it. Ideas?