title: Generic methods in conjunction with generic containers
body: <p>I currently have a class that contain a specific Collection implementation, much like the following example:</p>
  
  <pre><code>public class Bag {
  
      Set&lt;?&gt; items;
  
      public &lt;T&gt; Set&lt;T&gt; getItems() {
          return (Set&lt;T&gt;) items;
      }
  }
  </code></pre>
  
  <p>I now need to generalise the container, but I have troubles understanding how to obtain a similar getItems() method:</p>
  
  <pre><code>public abstract class AbstractBag&lt;S extends Collection&lt;?&gt;&gt; {
  
      S items;
  
      public &lt;T&gt; S&lt;T&gt; getItems(){  // &lt;- does not compile
          return (S&lt;T&gt;) items;
      }
  }
  </code></pre>
  
  <p>The final aim is to obtain the same original Bag, or Bag with other containers, as follow:</p>
  
  <pre><code>public class SetBag extends AbstractBag&lt;Set&lt;?&gt;&gt; {}
  public class ListBag extends AbstractBag&lt;List&lt;?&gt;&gt; {}
  </code></pre>
  
  <p>Is it possible?
  Thanks.</p>
  
  <p>EDIT: I will provide more details on why (I think) this code is necessary. I have a class that need to support attributes of any type. These attributes are a collection of values of that particular type (e.g. a set of strings, a set of integers, or a set of WhateverClass). I have a map that stores this data associated to a given key. It is then possible to retrieve the data by calling the key and casting the return object correctly. For convenience, this is done through the generic method above.</p>
  
  <p>Now, I need to have a second class where the collection type is different. To avoid code repetition (much more code than what is here), I would like to create an abstract class that has the collection as a generic type (like AbstractBag), and obtain the two classes with different containers (for instance one with Lists and one with Sets) as done for SetBag and ListBag.</p>