本帖最后由 邵阳 于 2012-7-19 11:16 编辑
第一个问题
这是一个TreeSet排序的代码。
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 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 this.name;
}
public int getAge()
{
return this.age;
}
}
class Test
{
public static void sop(Object o)
{
System.out.println(o);
}
public static void main(String[]args)
{
TreeSet trr=new TreeSet();
trr.add(new Student("lisi23",23));
trr.add(new Student("lisi25",25));
trr.add(new Student("llsi22",22));
trr.add(new Student("lisi24",24));
//trr.add(new Student("lisi24",24));
//trr.add(new Student("lisi20",24));
Iterator it=trr.iterator();
while (it.hasNext())
{
Student stu=(Student)it.next();
sop(stu.getName()+"::::"+stu.getAge());
}
}
}
输出结果是
D:\java\zuoye\jihe_set>java Test
lisi23.......compareTo........lisi23 //我不明白这里为什么自己跟自己比较了一次,毕老师的怎么都没有比较啊。哪里不一样啊?怎么改正能够使自己跟自己不用比较一次啊?
lisi25.......compareTo........lisi23
llsi22.......compareTo........lisi23
lisi24.......compareTo........lisi23
lisi24.......compareTo........lisi25
llsi22::::22
lisi23::::23
lisi24::::24
lisi25::::25
第二个问题
import java.util.*;
class Student
{
private String name;
private int age;
Student (String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class Test
{
public static void sop(Object o)
{
System.out.println(o);
}
public static void main(String[]args)
{
TreeSet trr=new TreeSet(new MyCompare());
trr.add(new Student("lisi23",23));
trr.add(new Student("lisi25",25));
trr.add(new Student("llsi22",22));
trr.add(new Student("lisi24",24));
Iterator it=trr.iterator();
while (it.hasNext())
{
Student stu=(Student)it.next();
sop(stu.getName()+"::::"+stu.getAge());
}
}
}
class MyCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.getName().compareTo(s2.getName());
}
}
为什么输出结果是
D:\java\zuoye\jihe_set>java Test
lisi23::::23
lisi24::::24
lisi25::::25
llsi22::::22
不是按姓名排序吗,怎么最后一个没有排序啊?找不出问题所在啊?代码也没错啊
|
|