本帖最后由 从前有个人 于 2013-11-18 20:10 编辑
package temptest;
import java.util.*;
class TempForTest {
static void sop(Object obj){
System.out.println(obj);
}
public static void main(String[] argus){
TreeSet ts = new TreeSet();
ts.add(new Students("san03",33));
ts.add(new Students("milo",33));
ts.add(new Students("san01",11));
Iterator it = ts.iterator();
while(it.hasNext()){
Students stu = (Students)it.next();
sop(stu.getName()+" "+stu.getAge());
}
}
}
class Students implements Comparable{ //该接口强制让学生具备比较性
private String name;
private int age;
Students(String name, int age){
this.name = name;
this.age = age;
}
public int compareTo(Object obj){
if(!(obj instanceof Students)) //为啥要写这句
throw new RuntimeException("不是学生对象");
Students s = (Students)obj;
if(this.age - s.age == 0){
return this.name.compareTo(s.name);
}
else
return this.age - s.age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
毕老师视频中为什么要写那句加深的判断代码呢?容器中添加的如果不是Students类的对象怎么能调用到这个方法呢,既然必须是Strudents的对象才能调用,为啥还要判断呢?如果是我的理解有问题,谁能帮我实现一下抛出异常的情况。
|