【发布时间】:2017-06-28 21:33:18
【问题描述】:
我有一个类Product,其中三个变量:
class Product implements Comparable<Product>{
private Type type; // Type is an enum
Set<Attribute> attributes; // Attribute is a regular class
ProductName name; // ProductName is another enum
}
我使用 Eclipse 自动生成 equal() 和 hashcode() 方法:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (attributes == null) {
if (other.attributes != null)
return false;
} else if (!attributes.equals(other.attributes))
return false;
if (type != other.type)
return false;
return true;
}
现在在我的应用程序中,我需要对一组产品进行排序,因此我需要实现 Comparable 接口和 compareTo 方法:
@Override
public int compareTo(Product other){
int diff = type.hashCode() - other.getType().hashCode();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
}
diff = attributes.hashCode() - other.getAttributes().hashCode();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
}
return 0;
}
这种实现有意义吗?如果我只想根据“类型”和“属性”值的字符串值对产品进行排序呢?那么如何实现呢?
编辑: 我想对 Set 进行排序的原因是因为我有 Junit 测试,它对 HashSet 的字符串值进行断言。我的目标是在对集合进行排序时保持相同的输出顺序。否则,即使 Set 的值相同,由于 set 的随机输出,断言也会失败。
编辑2: 通过讨论,很明显,在单元测试中断言 HashSet 的 String 值相等是不好的。对于我的情况,我目前编写了一个 sort() 函数来按自然顺序对 HashSet 字符串值进行排序,因此它可以始终如一地为我的单元测试输出相同的字符串值,现在就足够了。谢谢大家。
【问题讨论】:
-
你为什么曾经在 compareTo 中使用 hashCode?没有意义。什么需要按 hashCode 排序?类的“自然”顺序如何?
-
好的。没有意义。如何实现类的自然排序?
-
所以要回答你的问题,你的实现绝对没有意义。
-
您希望如何订购?依据什么标准? 这是最重要的,也是您应该在 compareTo 中使用的内容。
-
@user697911:您的班级在逻辑上是否具有自然顺序?你想按什么排序?
标签: java equals hashset hashcode