我需要编写一个比较器,它接受类型 A 的对象 A 和类型 B 的对象 B。这两个对象不是公共对象的扩展。它们确实不同,但我需要通过其中的共同字段来比较这两个对象。我必须使用比较器接口,因为对象存储在 Set 中,并且之后我必须使用 CollectionUtils 进行操作。我在谷歌上搜索了一下,找到了比较器的解决方案,但仅限于相同类型。
我试图朝这个方向进行思考,但我不知道我是否走在正确的道路上。
public class MyComparator implements Comparator<A>, Serializable {
private B b;
public MyComparator(B b){
this.b = b;
}
@Override
public int compare(A old, A otherOne) {
int value = 0;
if (!old.getField().equals(b.getField())) {
value = 1;
}
return value;
}
}
有可能总是给出答案,但我在谷歌中没有找到合适的词来搜索。有人建议吗?
Txs
P.S:我将两个对象添加到不同的集合中:
TreeSet<A> setA = new TreeSet<A>(myComparator);
TreeSet<B> setB = new TreeSet<B>(myComparator);
之后我会做这样的事情:
TreeSet<??????> retain = CollectionUtils.retainAll(setA, setB);
TreeSet<??????> remove = CollectionUtils.removeAll(setA, setB);
有一种非常hacky的方法可以让你使用Object
and instanceof
但如果您可以实现一个公开特定接口的代理类,那么最好这样做。
class A {
public String getSomething() {
return "A";
}
}
class B {
public String getSomethingElse() {
return "B";
}
}
class C implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
// Which is of what type?
A a1 = o1 instanceof A ? (A) o1: null;
A a2 = o2 instanceof A ? (A) o2: null;
B b1 = o1 instanceof B ? (B) o1: null;
B b2 = o2 instanceof B ? (B) o2: null;
// Pull out their values.
String s1 = a1 != null ? a1.getSomething(): b1 != null ? b1.getSomethingElse(): null;
String s2 = a2 != null ? a2.getSomething(): b2 != null ? b2.getSomethingElse(): null;
// Compare them.
return s1 != null ? s1.compareTo(s2): 0;
}
}
更可接受的机制是为每个实现公共接口的代理类实现一个代理类,然后可以使用适当的类型安全比较器进行比较。
interface P {
public String getValue();
}
class PA implements P {
private final A a;
PA(A a) {
this.a = a;
}
@Override
public String getValue() {
return a.getSomething();
}
}
class PB implements P {
private final B b;
PB(B b) {
this.b = b;
}
@Override
public String getValue() {
return b.getSomethingElse();
}
}
class PC implements Comparator<P> {
@Override
public int compare(P o1, P o2) {
return o1.getValue().compareTo(o2.getValue());
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)