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