1. 程式人生 > >ArrayList的練習 編寫程式實現對Employee類的排序

ArrayList的練習 編寫程式實現對Employee類的排序

練習題: 編寫程式實現對Employee類的排序,要求如下:

a) 給Employee類新增屬性:name:String,age:int,salary:double 

b) 把若干Employee物件放在List中,排序並遍歷輸出,排序規則:salary高的在前,salary相同時age大的在前面,age也相同時按照name升序排列

c) 把若干Employee物件放在HashSet中並遍歷輸出,要求沒有重複元素

程式碼如下:

package com.my.day7_16task;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

public class ArrayListTest {

	public static void main(String[] args) {
		
		Employee emp1 = new Employee("aa", 19, 1000);
		Employee emp2 = new Employee("bb", 32, 5000);
		Employee emp3 = new Employee("cc", 23, 3000);
		Employee emp4 = new Employee("ae", 20, 1000);
		Employee emp5 = new Employee("fd", 19, 5000);
		Employee emp6 = new Employee("khg", 19, 1000);
		
		List<Employee> al = new ArrayList<Employee>();
		
		al.add(emp1);
		al.add(emp2);
		al.add(emp3);
		al.add(emp4);
		al.add(emp5);
		al.add(emp6);
		
		System.out.println("姓名    年齡    薪資");
		for(Employee k: al){
			System.out.println(k);
		}
		
		System.out.println("---------------------");

		Comparator<Employee> comparator = new Comparator<Employee>(){
			public int compare(Employee e1, Employee e2) {
					//先排薪水 高-》低
				if(e1.getSalary()!=e2.getSalary()){
					return (int) (e2.getSalary()-e1.getSalary());
				}
				else if(e1.getAge()!= e2.getAge()){
					//薪水相同則按年齡排序 大-》小
					return e2.getAge()-e1.getAge();
				}
				else
					// if(!e1.getName().equals(e2.getName()))
					//年齡也相同則按姓名排序
					return (int)(e1.getName().compareTo(e2.getName()));
			}	
		};
		
		Collections.sort(al,comparator);	

		for(int i =0; i<al.size(); i++){
			System.out.println("職員的名字是:"+al.get(i).getName()+" 年齡:"
					+al.get(i).getAge()+" 薪水為:"+al.get(i).getSalary());
		}
	
	}
}

class Employee {

	private String name;
	private Integer age;
	private double salary;
	
	public Employee (String name, Integer age, double salary){
		this.age = age;
		this.name = name;
		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 double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	
	public String toString(){
		  return name+"  "+age+"  "+salary;
		 }
}

輸出如下:

姓名  年齡  薪資

aa  19  1000.0

bb  32  5000.0

cc  23  3000.0

ae  20  1000.0

fd  19  5000.0

khg  19  1000.0

---------------------

職員的名字是:bb 年齡:32 薪水為:5000.0

職員的名字是:fd 年齡:19 薪水為:5000.0

職員的名字是:cc 年齡:23 薪水為:3000.0

職員的名字是:ae 年齡:20 薪水為:1000.0

職員的名字是:aa 年齡:19 薪水為:1000.0

職員的名字是:khg 年齡:19 薪水為:1000.0