Common return value (java)

This works well:

// 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 "special" version could 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 a return value, ICode

I would like to return a value <? extends ICode>

. It can be done?

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

// 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;
    }

      

+2


source to share


2 answers


I am assuming you want it to be the same type as the actual list. In this 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;
}

      

+5


source


If you specify a return type in ICode, you can return any type that extends ICode.



0


source







All Articles