title: How do I return an object as its type from a list of its supertype?
body: <p>Say I have a class structure like so</p>
  
  <pre><code>public abstract class A
  {
      public String id;
  }
  
  public class B extends A
  {
      id = "b";
  }
  
  public class C extends A
  {
      id = "c";
  }
  
  public class test
  {
      ArrayList&lt;A&gt; as = new ArrayList&lt;A&gt;();
      a.add(new B());
      a.add(new C());
  
      public *what goes here* get(String s)//returns a subtype of A, not A
      {
          for(A a : as)
          {
              if(a.id.equals(s))//or a.getClass().toString()
              {
                  return a;//but need as subtype of A, not A
              }
          }
          //throw some exception here when id is not found
      }
  }
  </code></pre>
  
  <p>How do I make it so that if I ran </p>
  
  <pre><code>B b = get("b"); 
  </code></pre>
  
  <p>I would not get a compiler warning here? I don't want to have ugly instanceof checking all over my code, and explicitly casting to B is also not what I want. I think generics might be the way to go but I'm not very experienced with them. </p>
  
  <p>I know this doesn't work but this is the kind of thing I'm looking for</p>
  
  <pre><code>public T extends A get(String s)
  </code></pre>
  
  <p>where T extends A is the return type</p>