注册 登录
编程论坛 JAVA论坛

错误: Student不是抽象的, 并且未覆盖Comparable中的抽象方法compar eTo(Student)

maojianxin 发布于 2017-11-13 14:03, 2343 次点击
import java.util.*;
class Student implements Comparable<Student>
{
    private String name;
    private int age;
    Student(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
   
    public int compareTO(Student s)
    {
        int num = new Integer(this.age).compareTO(new Integer(s.age));
        
        if(num==0)
            return this.(s.name);
        return num;
    }
   
    public int hashCode()
    {
        return name.hashCode()+age*34;
    }
    public boolean equals(Object obj)
    {
        if(!(obj instanceof Student))
            throw new ClassCastException("类型不匹配");
        
        Student s = (Student)obj;
        
        return this.name.equals(s.name) && this.age==s.age;
    }
   
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public String toString()
    {
        return name+":"+age;
    }
   
}



class MapTest
{
    public static void main(String[] args)
    {
        HashMap<Student,String> hm = new HashMap<Student,String>();
        
        hm.put(new Student("lisi1"),"beijing");
        hm.put(new Student("lisi2"),"shanghai");
        hm.put(new Student("lisi3"),"nanjing");
        hm.put(new Student("lisi4"),"wuhan");
        
        //第一种取出方式 keySet
        
        Set<Student> keySet = hm.keySet();
        
        Iterator<Student> it = keySet.iterator();
        
        while(it.hashNext())
        {
            Student stu = it.next();
            String addr = hm.get(stu);
            System.out.println(stu+".."+addr);
        }
        
    }
}
2 回复
#2
maojianxin2017-11-13 14:06
在线等 新手 求大神指教!谢谢了
#3
林月儿2017-11-15 00:37

    public int compareTO(Student s)
    {
        int num = new Integer(this.age).compareTO(new Integer(s.age));
        
        if(num==0)
            return this.(s.name);
        return num;
    }
   
1