当前位置: 代码迷 >> Java相关 >> 自定义类用比较器(Comparator)出错,怎么回事?
  详细解决方案

自定义类用比较器(Comparator)出错,怎么回事?

热度:761   发布时间:2010-12-09 23:24:44.0
自定义类用比较器(Comparator)出错,怎么回事?
import java.util.*;
class TreeSetTest
{
    public static void main(String[] args)
    {
        //方法1 运用比较器
        TreeSet<Object> ts=new TreeSet<Object>(new Student.StudentComparator());
        
        //方法2 (由于实现了Comparable接口中的compareTo()方法,直接正常定义TreeSet的对象即可)
        //TreeSet<Object> ts=new TreeSet<Object>();
        ts.add(new Student(1,"lisi"));
        ts.add(new Student(2,"wangwu"));
        ts.add(new Student(3,"zhangsan"));
        ts.add(new Student(3,"mybole"));
        
        Iterator it=ts.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
        
    }
}

class Student implements Comparable
{
    int num;
    String name;
   
    static class StudentComparator implements Comparator//定义一个内部类实现Comparator接口
    {
        public int compare(Object o1,Object o2)
        {
            Student s1=(Student)o1;
            Student s2=(Student)o2;   
            
            int result=s1.num>s2.num?1:(s1.num==s2.num?0:-1);
            if(result==0)
            {
                result=s1.name.compareTo(s2.name);
            }
            return result;   
        }
    }
    Student(int num,String name)
    {
        this.num=num;
        this.name=name;
    }
   
  public String toString()
    {
        return "num="+num+","+"name="+name;
    }
   
    public int compareTo(Object o)
    {
        Student s=(Student)o;
        
        //return num>s.num?1:(num==s.num?0:-1);
        
        int result=num>s.num?1:(num==s.num?0:-1);
        if (result==0)
        {
            result= name.compareTo(s.name);
        }
        return result;
    }
}

用方法2没问题,程序运行正确。  
但用方法1时,编译的时候出错:使用了未经检查或不安全的操作。
改成了TreeSet<Object> ts=new TreeSet<Object>(new Student.StudentComparator<Object>());时
编译还是出错:Student.StudentComparator不带有参数。

额...头都晕了,我觉得是编译器版本的问题,怎么改才行啊,请大家指点下,谢谢了!!
搜索更多相关的解决方案: Comparator  比较器  定义  

----------------解决方案--------------------------------------------------------
这么多天了,怎么都没人回答啊,着急哦!!
----------------解决方案--------------------------------------------------------
  相关解决方案