我正在尝试覆盖参数化类的equals方法。
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Tuple))
return false;
Tuple<E> other = (Tuple<E>) obj; //unchecked cast
if (!a0.equals(other.a0) && !a0.equals(other.a1)) {
return false;
}
if (!a1.equals(other.a1) && !a1.equals(other.a0)) {
return false;
}
return true;
}如何确保other对象的<E>与this相同
发布于 2009-10-27 12:56:52
您可以通过保留对Class<E>类型的引用来完成此操作。然而,在我看来,相等性测试应该是关于对象表示的值,而不是值所表示的具体类型。
例如,Collections API就是一个典型的例子。new ArrayList<String>().equals(new LinkedList<Object>())返回true。虽然它们具有完全不同的类型,但它们代表相同的值,即“一个空集合”。
就个人而言,表示相同数据的两个Tuple(例如("a", "b"))是否不相等,因为一个是Tuple<String>类型,而另一个是Tuple<Object>类型
发布于 2009-10-27 12:12:54
你能做的最好的事情就是在元组类中存储你计划让元组保存在"java.lang.Class“字段成员中的类型。然后,您可以比较这些字段,以确保元组类包含相同的类型。
另请参阅此线程:What is the equivalent of the C++ Pair in Java?
如果你发布更多关于你的课程的信息将会有所帮助。我在想,未检查的类型转换和您等于的字段数量意味着它应该是Tuple不是吗?
编辑:这是我经常使用的一个有用的配对类(如果需要,你可以调整你的Tuple类)。注意,类似于其他人的建议,这个类只是让被包含的成员决定平等的问题。您的用例应该决定相等性是否真的基于所包含成员的类型。
/**
* Adapted from http://forums.sun.com/thread.jspa?threadID=5132045
*
*
* @author Tim Harsch
*
* @param <L>
* @param <R>
*/
public class Pair<L, R> {
private final L left;
private final R right;
public R getRight() {
return right;
} // end getter
public L getLeft() {
return left;
} // end getter
public Pair(final L left, final R right) {
this.left = left;
this.right = right;
} // end constructor
public static <A, B> Pair<A, B> create(A left, B right) {
return new Pair<A, B>(left, right);
} // end factory method
@Override
public final boolean equals(Object o) {
if (!(o instanceof Pair<?,?>))
return false;
final Pair<?, ?> other = (Pair<?, ?>) o;
return equal(getLeft(), other.getLeft()) && equal(getRight(), other.getRight());
} // end method
public static final boolean equal(Object o1, Object o2) {
if (o1 == null) {
return o2 == null;
}
return o1.equals(o2);
} // end method
@Override
public int hashCode() {
int hLeft = getLeft() == null ? 0 : getLeft().hashCode();
int hRight = getRight() == null ? 0 : getRight().hashCode();
return hLeft + (37 * hRight);
} // end method
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('<');
if( left == null ) {
sb.append("null");
} else {
sb.append(left.toString());
} // end if
sb.append(',');
if( right == null ) {
sb.append("null");
} else {
sb.append(right.toString());
} // end if
sb.append('>');
return sb.toString();
} // end method
} // end class发布于 2011-12-23 07:59:19
我自己也遇到了这个问题,在我的特殊情况下,我不需要知道类型E。
例如:
public class Example<E> {
E value;
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Example<?> other = (Example<?>) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}在上面的代码中,由于使用了Example<?>,所以没有未检查的强制转换。类型参数通配符'?‘拯救了一天。
https://stackoverflow.com/questions/1628718
复制相似问题