title: Interface on getter and setter of generic List type
body: <p>We're trying to extract an interface in a library containing versioned sets of beans (used in an XML webservice). The models themselves use only other models from the same version.</p>
  
  <p>There are mostly only getters and setters, and as the versions are quite similar, the process works well most of the time. There is a bit of a hiccup as it comes to List types though.</p>
  
  <p>Let's take an example:</p>
  
  <pre><code>public class Attribute implements IAttribute
  </code></pre>
  
  <p>This is used elsewhere:</p>
  
  <pre><code>public class Product implements IProduct {
      List&lt;Attribute&gt; products = new ArrayList&lt;Attribute&gt;();
  }
  </code></pre>
  
  <p>The interface IProduct has this getter and setter:</p>
  
  <pre><code>public interface IProduct {
      public abstract List&lt;? extends IAttribute&gt; getAttributes();
      public abstract void setAttributes(List&lt;? extends IAttribute&gt; attributes);
  }
  </code></pre>
  
  <p>The class Product then has this getter and setter:</p>
  
  <pre><code>public List&lt;Attribute&gt; getAttributes() {
      return attributes;
  }
  
  public void setAttributes(List&lt;? extends IAttribute&gt; attributes) {
      this.attributes = attributes;
  }
  </code></pre>
  
  <p>There is, of course, an error on the setter: the field attributes in Product is a List of Attribute, and is narrower than a List of wildcard extending IAttribute. It feels like a catch 22 though. If we widen the declaration of the field itself, we lose the benefit of specificity. There are then also issues implementing an add method (addAttribute(Attribute attribute)).</p>
  
  <p>One ugly solution would be to iterate over the List of wildcard extending IAttribute, do type checking and add only if the actual type of the objects inside are Attribute of the correct version. </p>
  
  <pre><code>public void setAttributes(List&lt;? extends IAttribute&gt; attributes) {
      this.attributes = new ArrayList&lt;Attribute&gt;();
      for (Attribute attribute : attributes) {
          if (!(attribute instanceof Attribute)) {
              throw new IllegalArgumentException();
          } else {
              this.attributes.add((Attribute)attribute);
          }
      }
  }
  </code></pre>
  
  <p>Is there a better, more robust, more elegant way to do this?</p>