如代码:
class MyPerson implements Comparable{
private int myAge;
public int getMyAge() {
return myAge;
}
public void setMyAge(int myAge) {
this.myAge = myAge;
}
public MyPerson(){
myAge = 0;
}
public MyPerson(int myAge){
this.myAge = myAge;
}
public int compareTo(MyPerson myperson){
return this.myAge - myperson.getMyAge();
}
public String toString() {
return "this people's age is " + myAge;
}
}
public class TreeSetTest {
public static void main(String[] argv){
TreeSet myTreeSet2 = new TreeSet(new myComparator());
MyPerson myPerson1 = new MyPerson(10);
MyPerson myPerson2 = new MyPerson(20);
myTreeSet2.add(myPerson1);
myTreeSet2.add(myPerson2);
myPerson1.setMyAge(30);
System.out.println(myTreeSet2);
}
}
执行后输出的为:
[this people's age is 20, this people's age is 30]
求问,HashSet是如何知道Person类的age变量被修改,及内部元素之间调用compareto函数的结果发生了变化?
关于HashMap中元素修改的监控
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- danielinbiti 2015-03-28 08:32关注
1、treeset只知道有person,是不可能关系person中的某个属性改变的。顺序在add进去的时候会进行排序,然后决定顺序。
2、person2在person1前面,只可能是你的myComparator这个排序规则导致。在修改成age等于30前就已经决定了顺序。解决 无用评论 打赏 举报