今天在电脑上敲代码输出结果与视频不一致:我的输出结果是这样:
lisi01....compareTo....lisi01
lisi007....compareTo....lisi01
lisi09....compareTo....lisi01
lisi09....compareTo....lisi007
lisi99....compareTo....lisi007
lisi99....compareTo....lisi09
lisi19....compareTo....lisi007
lisi19....compareTo....lisi01
lisi39....compareTo....lisi007
lisi39....compareTo....lisi01
lisi39....compareTo....lisi19
lisi49....compareTo....lisi007
lisi49....compareTo....lisi19
lisi49....compareTo....lisi01
lisi09....19
lisi99....19
lisi007....20
lisi49....20
lisi01....22
lisi19....29
lisi39....39
毕老师讲课视频输出结果没有第一行,第一行是向TreeSet集合中存入第一个元素,按说应该没有第一行的比较,哪位能否解释下;另往里存最后一个元素new Student("lisi49",20)时,因与(“lisi007”....20)年龄相同,所以与(“lisi007”....20)比较名字,而后不就应该排在(“lisi007”....20)之后了么,为何还会有最后两行输出结果的比较?
我的源代码如下:- package day15;
- import java.util.*;
- /*
- * 需求:往TreeSet集合中存储自定义对象学生
- * 按照学生的年龄进行排序
- */
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
- TreeSet ts=new TreeSet();
- ts.add(new Student("lisi01",22));
- ts.add(new Student("lisi007",20));
- ts.add(new Student("lisi09",19));
- ts.add(new Student("lisi99",19));
- ts.add(new Student("lisi19",29));
- ts.add(new Student("lisi39",39));
- ts.add(new Student("lisi49",20));
- Iterator it=ts.iterator();
- while(it.hasNext())
- {
- Student stu=(Student)it.next();
- System.out.println(stu.getName()+"...."+stu.getAge());
- }
-
- }
- }
- 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 s=(Student)obj;
- System.out.println(this.name+"....compareTo...."+s.name);
- if(this.age>s.age)
- return 1;
- if(this.age==s.age)
- {
- return this.name.compareTo(s.name);
- }
-
- return -1;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码 |