当前位置: 动力学知识库 > 问答 > 编程问答 >

Generic return value (java)

问题描述:

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;

}

网友答案:

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;
}
网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: