}
class Student implements Comparable{
private String name;
private int age;
Student(String name,int age){
this.name=name;
this.age=age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
if(!(o instanceof Student))
throw new RuntimeException("it is error!!!");
Student s=(Student) o;
System.out.println(this.getName()+"...compareTo..."+s.getName());
if(this.getAge()>s.getAge())
return 1;
else if(this.getAge()==s.getAge()){
return this.getName().compareTo(s.getName());
}
return -1;
}
}
class myCompare implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if(o1 instanceof Student && o2 instanceof Student)
throw new RuntimeException("The type is not match!!!");//为什么加上这两句话后会发生异常呢?
Student s1=(Student)o1;
Student s2=(Student)o2;
int num=s1.getName().compareTo(s2.getName());
if(num==0)
return s1.getAge()-s2.getAge();
return num;
}
if (o1 instanceof Student && o2 instanceof Student)
throw new RuntimeException("The type is not match!!!");
Student s1 = (Student) o1;
Student s2 = (Student) o2;
int num = s1.getName().compareTo(s2.getName());
if (num == 0)
return s1.getAge() - s2.getAge();
return num;
}
}
复制代码
作者: 郭军亮 时间: 2013-5-17 20:54
if (o1 instanceof Student && o2 instanceof Student)
throw new RuntimeException("The type is not match!!!");
为什么这里会报错呢?还是不太明白啊作者: 花开花落总相似 时间: 2013-5-17 22:57 本帖最后由 花开花落总相似 于 2013-5-17 23:41 编辑
if (o1 instanceof Student && o2 instanceof Student)
throw new RuntimeException("The type is not match!!!");
前面写错了 你改为
if(!(o1 instanceof Student) && !(o2 instanceof Student)) 试一下 作者: 黑马伍哲沂 时间: 2013-5-18 08:47
郭军亮 发表于 2013-5-17 20:54
if (o1 instanceof Student && o2 instanceof Student)
throw new RuntimeExcepti ...
throw new RuntimeException("The type is not match!!!");:L因为你自己在这里抛了异常啊!!! 你没看到抛的异常里面有"The type is not match:L这是你自己写的异常。。。。作者: 郭军亮 时间: 2013-5-18 10:21
哦哦哦 ,我的错,谢谢了