题目:编写一个类employee,该类拥有属性salary,请用Collection 保存多个 Employee,根据salary属性排序,并迭代输出salary值。
比较基础的编程题,用java7写的答案,比较满足各类面试题。
class Employee
{
private int salary;
public Employee() { }
public Employee(int salary)
{ this.salary = salary; }
public void setSalary() { this.salary = salary; }
public void getSalary() { return this.salary; } }
public class ListText {
public static void main(String[] args) {
Employee em1=new Employee(3400);
Employee em2=new Employee(2800);
Employee em3=new Employee(3460);
List list=new ArrayList();
list.add(em1);
list.add(em2);
list.add(em3);
for (int j = 0; j < list.size(); j++) {
for (int i = 0; i < list.size()-1-j; i++) {
Employee emp1 = (Employee) list.get(i);
Employee emp2 = (Employee) list.get(i+1);
if(emp1.getSalary() < emp2.getSalary()){
list.set(i, emp2);
list.set(i+1, emp1);
}
}
Iterator it = list.iterator();
while (it.hasNext()) {
Employee emp = (Employee) it.next();
System.out.print(emp.getSalary() + "\n");
}
}
}