黑马程序员技术交流社区
标题:
接口实现问题
[打印本页]
作者:
ztwztw
时间:
2014-1-4 21:43
标题:
接口实现问题
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class PersonText {
public static void main(String[] args){
TreeSet ts = new TreeSet();
ts.add(new Student("zhawern",223));
ts.add(new Student("zhaan",243));
ts.add(new Student("zhandgan",23));
ts.add(new Student("zhangaan",63));
}
}
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 name;
}
public int getAge(){
return age;
}
public int comparaTo(Object obj){
if(obj instanceof Student){
throw new RuntimeException();
}
Student s = (Student)obj;
return this.name.compareTo(s.name);
}
}
这个程序哪里出错误了
作者:
hurryup
时间:
2014-1-4 21:51
if(obj instanceof Student){
应当是不匹配该条件才抛异常即if(!obj instanceof Student)
作者:
李兴
时间:
2014-1-4 22:04
你的代码中compar
a
To自定义方法
不是对Comparable接口的compareTo()方法的实现
所以报告接口方法compareTo没有实现错误
改为compareTo
public int compare[color=Blue][/color]To(Object obj){
if(obj instanceof Student){
throw new RuntimeException();
}
Student s = (Student)obj;
//return this.name.compareTo(s.name);
return 0;
}
复制代码
作者:
DOOR
时间:
2014-1-4 22:05
本帖最后由 DOOR 于 2014-1-4 22:09 编辑
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class PersonText {
public static void main(String[] args){
TreeSet ts = new TreeSet();
ts.add(new Student("zhawern",223));
ts.add(new Student("zhaan",243));
ts.add(new Student("zhandgan",23));
ts.add(new Student("zhangaan",63));
}
}
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 name;
}
public int getAge(){
return age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student))//这里注意一下
throw new RuntimeException();
Student s = (Student)obj;
int num = this.name.compareTo(s.name);
if(num==0)
{
return new Integer(this.age).compareTo(new Integer(s.age));
}
return num;
}
}
复制代码
//重新给你写了一个
作者:
净坛使者
时间:
2014-1-4 22:15
if(obj instanceof Student){
throw new RuntimeException();
}
Student s = (Student)obj;
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2