标题: TreeSet比较器问题 [打印本页] 作者: 徐然 时间: 2012-5-4 16:51 标题: TreeSet比较器问题 import java.util.*;
class Student
{
private String name;
private int age;
private int num;
Student(String name, int age,int num)
{
this.name=name;
this.age=age;
this.num=num;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int getNum()
{
return num;
}
}
class StuMessage
{
public static void main(String[] args)
{
TreeSet<Student> al = new TreeSet<Student>(new StuNumComparator()); //这里比较器不能实例化,编译提示比较器需要静态
al.add(new Student("zhangsan",20,80));
al.add(new Student("lisi",18,70));
for(Iterator<Student> it = al.iterator();it.hasNext(); )
{
Student s = it.next();
System.out.println(s.getName()+","+s.getAge()+","+s.getNum());
}
}
class StuNumComparator implements Comparator<Student> //这个是按照号码排列的比较器
{
public int compare(Student s1,Student s2)
{
int temp = new Integer(s2.getNum()).compareTo(new Integer(s1.getNum()));
if(temp==0)
return s1.getName().compareTo(s2.getName());
return temp;
}
}
}
class StuNumComparator implements Comparator<Student>//这个是按照号码排列的比较器
{
public int compare(Student s1,Student s2)
{
int temp = new Integer(s2.getNum()).compareTo(new Integer(s1.getNum()));
if(temp==0)
return s1.getName().compareTo(s2.getName());
return temp;
}
}
}
复制代码
作者: 何阳 时间: 2012-5-4 22:28
import java.util.*;
class Student
{
private String name;
private int age;
private int num;
Student(String name, int age,int num)
{
this.name=name;
this.age=age;
this.num=num;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int getNum()
{
return num;
}
}
class StuMessage
{
public static void main(String[] args)
{
TreeSet<Student> al = new TreeSet<Student>(new StuNumComparator()); //这里比较器不能实例化,编译提示比较器需要静态
al.add(new Student("zhangsan",20,80));
al.add(new Student("lisi",18,70));
for(Iterator<Student> it = al.iterator();it.hasNext(); )
{
Student s = it.next();
System.out.println(s.getName()+","+s.getAge()+","+s.getNum());
}
}
class StuNumComparator implements Comparator<Student> //这个是按照号码排列的比较器
{
public int compare(Student s1,Student s2)
{
int temp = new Integer(s2.getNum()).compareTo(new Integer(s1.getNum()));
if(temp==0)
return s1.getName().compareTo(s2.getName());
return temp;
}
}
}
//其实你的代码并没有错,你只不过将构造器的类写在class StuMessage里面了
/*E:\java>javac Demo2.java
Demo2.java:31: 无法从静态上下文中引用非静态 变量 this
TreeSet<Student> al = new TreeSet<Student>(new StuNumComparator());
//这里比较器不能实例化,编译提示比较器需要静态
^
1 错误