使用 Java 中的类型参数为 类 编写平等契约
Writing an equality contract for classes with type parameters in Java
tl;dr:如何在不引发 'unchecked cast' 警告的情况下转换具有类型参数的对象?即:
List<Foo> bar = (List<Foo>) obj;
编译器给我一个关于以下代码的 'unchecked cast' 警告。如何修复警告?在演员表前放置一个 @SuppressWarnings("unchecked")
将代表最可悲的解决方案。
public class Container<V> {
public V getV();
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Container<V> other = (Container<V>) obj;
return this.getV().equals(other.getV());
}
}
您不需要将其转换为 Container<V>
。无论如何,如果没有未经检查的转换警告,你不能将它转换为 Container<V>
,因为它可能是任何东西的 Container
。
但是当您在 getV
的 V
上延迟 equals
时,equals
将进行自己的类型检查(或者应该)。
你只需要将它转换为Container<?>
;让您调用的 equals
方法确保 other
的对象是 equal
到您自己的对象的 V
.
Container<?> other = (Container<?>) obj;
tl;dr:如何在不引发 'unchecked cast' 警告的情况下转换具有类型参数的对象?即:
List<Foo> bar = (List<Foo>) obj;
编译器给我一个关于以下代码的 'unchecked cast' 警告。如何修复警告?在演员表前放置一个 @SuppressWarnings("unchecked")
将代表最可悲的解决方案。
public class Container<V> {
public V getV();
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Container<V> other = (Container<V>) obj;
return this.getV().equals(other.getV());
}
}
您不需要将其转换为 Container<V>
。无论如何,如果没有未经检查的转换警告,你不能将它转换为 Container<V>
,因为它可能是任何东西的 Container
。
但是当您在 getV
的 V
上延迟 equals
时,equals
将进行自己的类型检查(或者应该)。
你只需要将它转换为Container<?>
;让您调用的 equals
方法确保 other
的对象是 equal
到您自己的对象的 V
.
Container<?> other = (Container<?>) obj;