这位兄弟你说的不对 TreeSet比较唯一用的就是compareTo(),TreeSet在存入元素的时候根本就不会调用equals方法。
我给你写个自己看下吧
- import java.util.*;
- class Student implements Comparable
- {
- private int age;
- private String name;
- Student(String name,int age)
- {
- this.age = age;
- this.name = name;
- }
- public int compareTo(Object obj)
- {
- System.out.println("compareTo");
- if(!(obj instanceof Student))
- throw new RuntimeException("不是学生类!!");
- Student s = (Student)obj;
- if(this.age>s.age)
- return 1;
- if(this.age==s.age)
- {
- return this.name.compareTo(s.name);
- }
- return -1;
- }
- public boolean equals(Object obj){
- System.out.println("我是equals");
- return false;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- class DemoTreeSet
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- ts.add(new Student("张三",18));
- ts.add(new Student("李四",19));
- ts.add(new Student("王五",19));
- ts.add(new Student("赵六",20));
- ts.add(new Student("赵六",20));//重复记录
- Iterator it = ts.iterator();
- while(it.hasNext())
- {
- Student s = (Student)it.next();
- System.out.println(s.getName()+"........"+s.getAge());
- }
- }
- }
- /*运行结果
- * compareTo
- compareTo
- compareTo
- compareTo
- 张三........18
- 李四........19
- 王五........19
- 赵六........20
- * */
复制代码
如果用到equals方法是会打印“我是equals”这句话的 |