本帖最后由 杨兴庭 于 2013-7-23 16:31 编辑
请设计一个具备比较功能的类(例如 员工类, 需要有姓名, 年龄, 薪水三个成员属性需要私有并提供get, set方法, 可以通过构造函数进行初始化,并且按照薪水进行排序
import java.util.*;
class Test7
{
public static void main(String[] args)
{
TreeSet<Woker> tm = new TreeSet<Woker>();
tm.add(new Woker("张三",23,5000));
tm.add(new Woker("李四",21,4000));
tm.add(new Woker("网的",24,5000));
tm.add(new Woker("读书手",22,3500));
tm.add(new Woker("低声说",22,4500));
Iterator<Woker> it = tm.iterator();
while(it.hasNext())
{
Woker stu = (Woker)it.next();
System.out.println(stu.getName()+"..."+stu.getAge()+"..."+stu.getPay());
}
}
}
class StuPayComparator implements Comparator<Woker>
{
public int compare(Woker s1,Woker s2)
{
int num = s1.getName().compareTo(s2.getName());
if(num==0)
return new Integer(s1.getPay()).compareTo(new Integer(s2.getPay()));
return num;
}
}
class Woker implements Comparable<Woker>
{
private String name;
private int age;
private int pay;
Woker(String name,int age,int pay)
{
this.name = name;
this.age = age;
this.pay=pay;
}
public int compareTo(Woker w)
{
if(this.pay>w.pay)
return 1;
if(this.age==w.age)
{
return this.name.compareTo(w.name);
}
return -1;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public int getPay()
{
return pay;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age=age;
}
public String toString()
{
return name+":"+age+":"+pay;
}
}
|