是否可以将以下函数创建为我可以重复使用的通用函数?
我想传入一个集合,并返回对象中特定属性的列表。
到目前为止我有这样的例子:
private List<Integer> getPropertyABCIdsFromSomeObject(List<SomeObject> someObjects) {
List<Integer> ids = new ArrayList<Integer>();
for(SomeObject so : someObjects) {
ids.add(so.getPropertyABCId());
}
return ids;
}
所以这个方法只适用于SomeObject类型,返回一个PropertyABCId列表。
现在,如果我想要一些其他属性的列表,我必须复制这个函数,只做很少的改动。
泛型可以挽救局面吗?
最佳答案
你需要一个接口(interface),但是是的:
interface HasProperty<T> {
T getProperty();
}
public static <T> List<T> getProperties(List<? extends HasProperty<T>> items) {
List<T> properties = new ArrayList<T>();
for (HasProperty<T> item : items) {
properties.add(item.getProperty());
}
return properties;
}
关于java - 如何创建创建列表的方法的通用版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13443726/