我有一个方法
<T> void f (Collection<T> c, T t)
唉,有时候我需要作为第一个参数传递的不是 Collection 而是 Collection,其中 P 是一个 precursor 对于 T,即有一个 P getter 方法返回一个 T。
那么我该如何修改我的方法以同时使用 Collection 和 Collection
例如,
<T> boolean f (Collection<T> c, T t) {
for (T x : c) if (x.equals(t)) return true;
return false;
}
class Z { String a, b; }
我希望能够使用 f 按 a 或 b 搜索 Collection
f(Collection<Z> c1 ???searching by a???, "foo")
f(Collection<Z> c2 ???searching by b???, "bar")
我无法控制T和P的实现;特别是,我不能让 P 从 T 继承(而且我不想:就像上面的 Z 一样,我可能想搜索在不同的时间通过不同的字段)。
我不想通过映射创建中间集合
我想要类似 common :key Lisp keyword argument 的东西.
最佳答案
如何使用谓词的接口(interface)之类的东西来检查相等性。一个例子是:
interface Predicate<T> {
public boolean test(T element);
}
然后使用下面的函数:
public <T> boolean f(Collection<T> c, Predicate<T> p) {
for (T x : c) if (p.test(x)) return true;
return false;
}
那么你可以通过以下方式调用它:
Collection<T> ts;
f(ts, new Predicate<T> () {
public boolean test(T element) {
return element.equals("foo");
}
});
Collection<P> ps;
f(ps, new Predicate<P> () {
public boolean test(P element) {
return element.getT().equals("foo");
}
});
虽然此语法非常冗长,但它应该适合您的问题。然而,当 lambda 函数到来时,它会在 Java 8 中变得更漂亮。
关于java - 在集合中使用 "precursor"类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10540996/