【发布时间】:2009-09-01 14:47:12
【问题描述】:
基本上我不想比较元素,而是你包含的元素。如果跟随会起作用,那就太酷了,但它不起作用。
public boolean equals(Ie<T> that) {
T This = this.value;
T That = that.value;
boolean x = That.compareTo(This) == 0;
return x;
}
我所做的是:
public boolean equals(Object obj) {
if (obj == null)
return false;
String tmp = obj.toString();
if (this.value instanceof Integer)
return equalsInt(new Ie<Integer>(Integer.parseInt(tmp)));
// etc.
return false;
}
public boolean equalsInt(Ie<Integer> ie) {
Integer This = this.value.intValue();
Integer That = ie.value;
boolean x = That.compareTo(This) == 0;
return x;
}
这是一个明显的蛮力解决方案。没有obj.toString();+新元素可以吗?
编辑:
Ie类定义为:
public static class Ie<T extends Number & Comparable<? super T>>
extends Number implements Comparable<Ie<T>> {
类与方法相比相当简单:
public int compareTo(Ie<T> that) {
T This = this.value;
T That = that.value;
return (This.compareTo(That) < 0 ? -1 : (This
.compareTo(That) > 0 ? 1 : 0));
}
我正在使用 Collection addall 方法中的类,其中 contains 正在调用 equals。
Erikson 解决方案运行良好:
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (this == that)
return true;
if (that instanceof Ie<?>) {
Object ThisValue = this.value;
Object ThatValue = ((Ie<?>) that).value;
return ThisValue.equals(ThatValue);
}
return false;
}
【问题讨论】:
-
我并没有真正理解你的问题和你的目标。您只想比较两个对象吗?如果是这样,您应该比较对象的每个属性。请澄清您的问题。