在下面的程序中添加代码,按照Employee的id排序
public class Test
{
public static Employee[] sort(Employee ee[]){
//...............添加代码处
return ee;
}
public static void main(String[] args) {
Employee ee[]={new Employee(1,100),new Employee(100,25),new Employee(50,123.3)};
sort(ee);
for(int i=0;i<ee.length;i++)
System.out.println(ee[i]);
}
}class Employee
{
private int id;
private double salary;
public Employee(int id, double salary) {
this.id = id;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String toString() {
// TODO Auto-generated method stub
return String.valueOf(id)+","+String.valueOf(salary);
}
}
public class Test
{
public static Employee[] sort(Employee ee[]){
//...............添加代码处
return ee;
}
public static void main(String[] args) {
Employee ee[]={new Employee(1,100),new Employee(100,25),new Employee(50,123.3)};
sort(ee);
for(int i=0;i<ee.length;i++)
System.out.println(ee[i]);
}
}class Employee
{
private int id;
private double salary;
public Employee(int id, double salary) {
this.id = id;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String toString() {
// TODO Auto-generated method stub
return String.valueOf(id)+","+String.valueOf(salary);
}
}
然后看看集合的sort方法
public static Employee[] sort(Employee ee[]){
for(int i=0;i<ee.length();i++){
//冒泡排序
}
return ee;
}
//Employee中的id属性不能设置为private,否则外部访问不到
public static Employee[] sort(Employee ee[]) {
// ...............添加代码处
Arrays.sort(ee, new Comparator(){
public int compare(Object o1, Object o2) {
int i = ((Employee)o1).id;
int j = ((Employee)o2).id;
return i - j;
}
});
return ee;
}
public static Employee[] sort(Employee ee[]) {
Arrays.sort(ee, new Comparator() {
public final int compare(Object obj1, Object obj2) {
Employee u1 = (Employee) obj1;
Employee u2 = (Employee) obj2;
int id1 = u1.getId();
int id2 = u2.getId();
return id1 - id2;
}
});
return ee;
}
private double salary;
public int compareTo(Object o){
Employee obj = (Employee)o;
if(obj.getId()>this.id)
return -1;
if(obj.getId()<this.id)
return 1;
if(obj.getSalary()>this.getSalary)
return -1;
if(obj.getSalary()<this.getSalary)
return 1;
return 0;
}
}
over~