jav*_*fun 5 java collections compare
我需要编写一个比较器,它采用类型 A 的对象 A 和类型 B 的对象 B。这两个对象不是公共对象的扩展。它们确实不同,但我需要通过其中的公共字段来比较这两个对象。我必须使用比较器接口,因为对象存储在 Set 中,并且在我必须使用 CollectionUtils 进行操作之后。我用谷歌搜索了一下,我找到了 Comparator 的解决方案,但只有相同的类型。
我试图在这个方向上实现一个想法,但我不知道我是否走在正确的道路上。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
有可能总是给出答案,但我没有在谷歌中找到合适的词来搜索。有人建议吗?
发送
PS:我在不同的 Set 中添加了两个对象:
TreeSet<A> setA = new TreeSet<A>(myComparator);
TreeSet<B> setB = new TreeSet<B>(myComparator);
Run Code Online (Sandbox Code Playgroud)
之后我会这样想:
TreeSet<??????> retain = CollectionUtils.retainAll(setA, setB);
TreeSet<??????> remove = CollectionUtils.removeAll(setA, setB);
Run Code Online (Sandbox Code Playgroud)
有一种非常hacky的方法可以让您使用Object,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;
}
}
Run Code Online (Sandbox Code Playgroud)
更可接受的机制是为每个实现公共接口的代理类实现一个代理类,然后可以使用适当的类型安全比较器进行比较。
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12440 次 |
| 最近记录: |