黑马程序员技术交流社区
标题:
在往TreeSet中添加对象时,第一个对象会与自己比较?
[打印本页]
作者:
李建强
时间:
2012-9-21 17:23
标题:
在往TreeSet中添加对象时,第一个对象会与自己比较?
本帖最后由 李建强 于 2012-9-23 11:05 编辑
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("张三",13));
ts.add(new Student("李四",14));
ts.add(new Student("王五",15));
ts.add(new Student("赵六",16));
ts.add(new Student("赵小六",16));
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;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
复制代码
在往TreeSet中添加对象时,第一个对象会与自己比较。
比如,TreeSet中只有张三这个对象,还是会与张三比较。
但是在myEclipse中就不会出现自己与自己比较的现象?
难道是1.7和1.6的区别?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2