Java 在方法定义中使用普通双函数可以做到这一点吗
我遇到了以下问题:一个方法应该包含一个bi函数,该函数包含两个参数——一个是Java 在方法定义中使用普通双函数可以做到这一点吗,java,generics,java-8,functional-interface,Java,Generics,Java 8,Functional Interface,我遇到了以下问题:一个方法应该包含一个bi函数,该函数包含两个参数——一个是Collection类型,另一个是T;实际的函数可以是Collection::remove或Collection::add,或更复杂的操作;实际函数用于十几个集合,函数中有几种类型的值和集合 最初没有泛型-只有Collections,元素是Strings,因此将参数声明为BiFunction效果很好: List<String> idCodes; void visitElement(Element e,
Collection
类型,另一个是T
;实际的函数可以是Collection::remove
或Collection::add
,或更复杂的操作;实际函数用于十几个集合,函数中有几种类型的值和集合
最初没有泛型-只有Collection
s,元素是String
s,因此将参数声明为BiFunction
效果很好:
List<String> idCodes;
void visitElement(Element e,
BiFunction<Collection<String>, String, Boolean> elementOp) {
elementOp.apply(idCodes, e.getIdCode());
}
但是失败了——我可能只是在某个地方得到编译错误,不管我对类型参数使用什么,它都会失败
我的一次尝试是
<T> void visitElement(Element e,
BiFunction<Collection<T>, T, Boolean> elementOp)
毫不奇怪,现在这正是我想要的。因此,我的问题是:
我真的要用吗
interface ElementOp {
<T> boolean apply(Collection<T> collection, T item);
}
void visitElement(Element e,
ElementOp elementOp) {
elementOp.apply(idCodes, e.getIdCode());
elementOp.apply(weights, e.getWeight());
}
interface ElementOp{
布尔应用(集合集合,T项);
}
无效访问(元素e,
ElementOp(元素操作){
elementOp.apply(idcode,例如getIdCode());
elementOp.apply(权重,例如getWeight());
}
或者在这种情况下可以使用双功能
另外,我使用的是Eclipse4.3MarsJava编译器,所以这可能是因为那里有一个bug而无法工作。您不能将
双函数
与T
泛型一起使用,以处理这两种情况(String
和Integer
)此代码无法编译:
<T> void visitElement(Element e,
BiFunction<Collection<T>, T, Boolean> elementOp) {
...
elementOp.apply(idCodes, e.getIdCode());
elementOp.apply(weights, e.getWeight());
}
这项工作:
elementOp.apply(idCodes, e.getIdCode());
elementOp.apply(weights, e.getWeight());
与BiFunction
相反,它可以接受任何类声明的任何变量作为参数。需要保留的是
ElementOp
不是泛型类。T
实际上只是一个泛型方法作用域,用于推断所传递参数的类型
为了满足您的需求:多次调用同一方法(
Collection.add()
或Collection.remove()
),但使用不同类型的参数(String
或Integer
),您不想使用通用的双函数
您引入的自定义功能界面更适合使用。您的第一次尝试没有成功,因为当您有这样的功能时:
<T> void visitElement(Element e, BiFunction<Collection<T>, T, Boolean> elementOp) {
// some code
}
并使用它:
BiConsumer<Collection<String>, String> bi = Collection::remove;
Element e = ...
Collection<String> idCodes...;
visitElement(e.getIdCode(), bi, idCodes);
BiConsumer bi=Collection::remove;
元素e=。。。
收集识别码。。。;
visitElement(例如getIdCode()、bi、idCodes);
elementOp.apply(idCodes, e.getIdCode());
elementOp.apply(weights, e.getWeight());
<T> void visitElement(Element e, BiFunction<Collection<T>, T, Boolean> elementOp) {
// some code
}
void visitElement(T value, BiConsumer<Collection<T>, T> elementOp, Collection<T> elements) {
elementOp.accept(elements, value);
}
BiConsumer<Collection<String>, String> bi = Collection::remove;
Element e = ...
Collection<String> idCodes...;
visitElement(e.getIdCode(), bi, idCodes);