import java.util.*;
class Student_1 implements Comparable
{
private String name;
private int age;
Student_1(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student_1))
throw new RuntimeException("bushi xueshengduixiang");
Student_1 s=(Student_1)obj;
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;
}
}
class TreeSetDemo1
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet(new MyCompare());
ts.add(new Student_1("lisi002",21));
ts.add(new Student_1("lisi03",22));
ts.add(new Student_1("lisi04",25));
ts.add(new Student_1("lisi005",26));
ts.add(new Student_1("lisi005",29));
Iterator it=ts.iterator();
while(it.hasNext())
{
Student_1 stu=(Student_1)it.next();
System.out.println(stu.getName()+"...."+stu.getAge());
}
}
}
class MyCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Student_1 s1=(Student_1)o1;
Student_1 s2=(Student_1)o2;
int num=s1.getName().compareTo(s2.getName());
if(num==0)
{
if(s1.getAge()>s2.getAge())
return 1;
if(s1.getAge()==s2.getAge());
return 0;
return -1;
}
return num;
}
}
编译报异常错误
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable code
但是把循环中的return -1;注释掉就可以通过这是怎么回事呢?
if(num==0)
{
if(s1.getAge()>s2.getAge())
return 1;
if(s1.getAge()==s2.getAge());
return 0;
return -1;
} |