2 Replies Latest reply: Aug 13, 2010 4:47 AM by 843793 RSS

    Iterating over a bounded wildcard type

    843793
      I'm trying to iterate over a collection of a bounded wildcard type and perform operations on the type. The code below doesn't compile - it breaks at compile time on the line
      final Iterator<? super Widget> i = widgets.iterator();
      with a Type mismatch error. I think what I'm trying to do is not possible because parameterized types are invariant. Will somebody please tell me I'm wrong? :-)
      public interface Widget {}
      public class WidgetImpl implements Widget {}
      
      public class WidgetFactory {
          public Collection<? extends Widget> getWidgets() { /* stuff */ }
      }
      
      public class WidgetConsumer {
          public void gogogo() {
              this.examineWidgets(WidgetFactory.getWidgets());
          }
      
          private void examineWidgets(final Collection<? super Widget>) {
              final Iterator<? super Widget> i = widgets.iterator();
              while (i.hasNext()) {
                  final Widget widget = i.next();
              }
          }
      }