本帖最后由 Sword 于 2013-6-6 18:54 编辑
知道是重写接口方法那得的问题,改了好久改不过来,求解
public class Student implements Comparable{
private String name;
private int age;
public Student(){};
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name ;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
//重写comparable接口的方法:
public int compareTo(Object obj) {
if(!(obj instanceof Student)){
Student s = (Student)obj;
if(this.age > s.age){
return 1;
}else if(this.age == s.age){
return this.name.compareTo(s.name);
}else{
return -1;
}
}
return age ; //应该是这的问题,毕老师的视频中if语句都没加{}我在MyEslise中加上就乱了 求解
}
}
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(new Student("张三",20));
ts.add(new Student("李四",22));
ts.add(new Student("王五",24));
ts.add(new Student("赵六",26));
ts.add(new Student("赵六",26));
for(Iterator it = ts.iterator(); it.hasNext();){
Student s = (Student)it.next();//向下转型
System.out.println(s.getName() + "-->" + s.getAge());
}
}
}
|