【发布时间】:2014-01-09 09:10:08
【问题描述】:
我有一个 Treeset,其中人们按他们的钱排序,但平等是基于名称的。
我有同名“jackie”的 jack 和 jackie,他们被认为是平等的。 jack 添加到树集中,jackie 没有。
contains() 上的 javadoc 说:
如果此集合包含指定元素,则返回 true。更多的 形式上,当且仅当此集合包含元素 e 时才返回 true 这样 (o==null ? e==null : o.equals(e))。
不幸的是行
System.out.println(peoples.contains(jackie));
当jackie.equals(jack) 返回真时返回假。为什么?
这是完整的代码。
public class UsingSet {
public static void main(String[] args) {
People jo = new People("Jo");
People jack = new People("Jackie");
jack.setMoney(12);
People jim = new People("Jimmy");
jim.setMoney(150);
People john = new People("John");
TreeSet<People> peoples = new TreeSet<People>();
peoples.add(jo);
peoples.add(jack);
peoples.add(jim);
peoples.add(john);
People jackie = new People("Jackie");
System.out.println("equality ? "+(jackie.equals(jack)));
System.out.println(peoples.contains(jackie));
}
}
class People extends Object implements Comparable<People> {
public static long maxCount() {
return 25000000000L;
}
String name;
Float money = 1000f;
public People(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.length());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(People other) {
int result = this.money.compareTo(other.getMoney());
if (result == 0){
//finding a second criteria
return this.name.compareTo(other.getName());
}else{
return result;
}
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
}
编辑:
javadoc 说基于 自然顺序 的 Treeset 必须具有与 compareTo() 一致的 equals()。带有Comparator 的 Treeset 一定不能。
所以我像这样稍微修改了代码:
Comparator<People> compareByMoney = new Comparator<People>() {
@Override
public int compare(People p1, People p2) {
int result = p1.money.compareTo(p2.getMoney());
if (result == 0){
//finding a second criteria
return p1.name.compareTo(p2.getName());
}else{
return result;
}
}
};
TreeSet<People> peoples = new TreeSet<People>(compareByMoney);
...
System.out.println(peoples.contains(jackie)); //--> true
【问题讨论】:
-
仅供参考,对我来说是正确的。 ideone.com/anwxoX
-
我更正了 main 的最后一行:我测试 System.out.println(peoples.contains(jackie));这是错误的
标签: java collections