今天分享的题目:
向TreeSet集合中加入5个员工的对象,根据员工的年龄(升序)进行排序,若年龄相同,再根据工龄(降序)来排序,若工龄相同,根据薪水(降序)排序。
/**
* 向TreeSet集合中加入5个员工的对象,根据员工的年龄(升序)进行排序,若年龄
* 相同,再根据工龄(降序)来排序,若工龄相同,根据薪水(降序)排序。
*/
//员工成员属性
public class EmploInf implements Comparable<EmploInf> {
private String name; //声明姓名
private int age; //年龄
private int worktime; //工龄
private int salary; //薪水
public EmploInf(String name, int age, int worktime, int salary) {
super();
this.name = name;
this.age = age;
this.worktime = worktime;
this.salary = salary;
}
//自动生成的一堆方法,必须要有的
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;
}
public int getWorktime() {
return worktime;
}
public void setWorktime(int worktime) {
this.worktime = worktime;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public EmploInf() {
super();
}
/* 重写compareTo方法,按照年龄升序,若年龄相同,再根据工龄降序来排序,若工龄相同,根据薪水降序排序 */
public int compareTo(EmploInf obj) { //compareTo()方法实现排序功能
if (this.age != obj.age) { //首先判断两个值是否相等
return this.age - obj.age; //结果为正,实现升序排列
} else {
if (this.worktime != obj.worktime) {
return -(this.worktime - obj.worktime); //结果为负,实现降序排列
} else {
return -(this.salary - obj.worktime);
}
}
}
@Override
public String toString() {
return "name=" + name + ", age=" + age + ", worktime=" + worktime + ", salary=" + salary;
}
}
/*主函数*/
public class EmployeeList {
public static void main(String[] args) {
// 创建一个TreeSet集合,使用Comparator接口的匿名内部类的匿名对象作为比较器
TreeSet<EmploInf> tree = new TreeSet<>();
// 添加元素
tree.add(new EmploInf("张三", 28, 7, 6750));
tree.add(new EmploInf("李四", 20, 2, 4500));
tree.add(new EmploInf("王五", 20, 1, 4000));
tree.add(new EmploInf("赵六", 20, 2, 4900));
tree.add(new EmploInf("于七", 22, 1, 4400));
// Iterator迭代器遍历(这个没啥好说的,格式就这样)
Iterator<EmploInf> it = tree.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
运行出来的结果:
输出有些不好看,设置的是默认的,大家可以修改 toString() 中的内容,改的好看一些(*^_^*)