为了账号安全,请及时绑定邮箱和手机立即绑定

TreeSet集合第一次增加对象时会调用compsareTo方法??

TreeSet集合第一次增加对象时会调用compsareTo方法??

qq_慕尼黑7072541 2016-12-26 21:46:11
import java.util.*; class Student implements Comparable { private String name; private int age; Student(String name,int age) { this.name = name; this.age = age; } public int compareTo(Object obj) { if(!(obj instanceof Student)) throw new RuntimeException("您输入的格式不正确"); Student stu = (Student)obj; System.out.println(this.name+"::::"+stu.name); //为了观察compareTo是怎么运行的 if (this.age>stu.age) { return 1; } if (this.age == stu.age) { return this.name.compareTo(stu.name); } return -1; } public String getName() { return name; } public int getAge() { return age; } } class TreeSetTest { public static void main(String[] args) { TreeSet ts = new TreeSet(); ts.add(new Student("lilei",9)); ts.add(new Student("hanmeimei",9)); ts.add(new Student("lilei001",9)); Iterator it = ts.iterator(); while (it.hasNext()) { Student s = (Student)it.next(); System.out.println(s.getName()+"::"+s.getAge()); } } } 显示的是第一个对象先和自己比较了?
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 961 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信