views:

262

answers:

2

This works nicely:

// Return all objects with code 'code'.
static List<? extends ICode> getObjects(String code, List<? extends ICode> list)
{
  <ICode> retValue = new ArrayList<ICode>();
  for (ICode item : list)
  { 
    if (item.getCode().equals(code))
    {
        retValue.add(item);
    }
  }
  return retValue;
}

The 'singular' version can be:

// Return the first object found with code 'code'.
static ICode getObject(String code, List<? extends ICode> lijst)
{
  for (ICode item : lijst)
{
     if (item.getCode().equals(code)) return item;
}
return null;
}

But instead of return value ICode I would like return value <? extends ICode>. Can it be done?

See Jon Skeets answer, I now prefer to use the T instead of ? also in the plural version:

// Return all objects with code 'code'.
    public static <T extends ICode> List<T> getObjects(String code, List<T> lijst)
    {
        List<T> retValue = new ArrayList<T>();
        for (T item : lijst)
        {
        if (item.getCode().equals(code))
        {
        retValue.add(item);
        }
      }
      return retValue;
    }
+5  A: 

I assume you want it to be the same type as the actual list. In that case, this should do it:

static <T extends ICode> T getObject(String code, List<T> list)
{
  for (T item : list)
  {
     if (item.getCode().equals(code)) return item;
  }
  return null;
}
Jon Skeet
compiler says 'set method return type to T':static <T extends ICode> T getObjecta rather strange notation
Gerard
strange that item.getCode() works, because as an input parameter it has not been declared that T implements ICode. Only for the return value??
Gerard
Wait a minute, I see the light. The first declaration is for the whole method signature, the following T is the one-character return value and the declaration also holds for T in the parameter list.
Gerard
Yes. It's the same type anywhere `T` is mentioned in the entire method.
Dirk
Even if you had a list of lists you'd want to ditch the wildcard in the return type: `static List<Code> findObjects(String name, List<? extends List<? extends Code>> list)`.
Tom Hawtin - tackline
A: 

If you let the return type be ICode then you can return any type that extends ICode.

Alexander Kjäll
That's the "singular version" he has already
Pete Kirkham
Which is not the same... Consider: a class `Subcode` which extends/implements `ICode` and `List<Subcode> list = ...`, then you can do `Subcode foo = getObject("foo", list)` but you would have to do `foo = (Subcode)getObject("foo", list)` with your solution.
Dirk
Correct, an extra cast is necessary. Compare to the List<? extends ICode> where a cast is not necessary.
Gerard