java对象数组排序

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test
{
public static void main(String[] args)
{
   Employee[] staff = new Employee[5];
   staff[0] = new Employee("Harry Hacker", 35000);
   staff[1] = new Employee("Carl Cracker", 75000);
   staff[2] = new Employee("Tony Tester", 38000);
   staff[3] = new Employee("Owen Leader", 95000);
   staff[4] = new Employee("GOGO dustman", 4000);
   /*List<Employee> list=new ArrayList<Employee>();
   list.add(new Employee("alvin",9999));
   list.add(new Employee("Harry Hacker",35000));
   list.add(new Employee("Cracker Hacker",75000));
   list.add(new Employee("Owen Hacker",95000));
   list.add(new Employee("GOGO Hacker",4000));
   Arrays.sort(list.toArray());*/
Array.sort(staff);//只能排列 数组->[]  不能排列 集合->List
   for (Employee e : staff)
   {
    System.out.println("name=" + e.getName() + ", salary=" + e.getSalary());
   }
   int[] array = new int[] { 5, 4, 8, 2, 7, 3, 1, 6 };
   Arrays.sort(array);
   for (int i : array)
   {
    System.out.println(i);
   }
}
}

class Employee implements Comparable<Employee>
{
public Employee(String n, double s)
{
   name = n;
   salary = s;
}

public String getName()
{
   return name;
}

public double getSalary()
{
   return salary;
}

public int compareTo(Employee other)
{
   if (salary < other.salary)
   {
    return -1;
   }
   if (salary > other.salary)
   {
    return 1;
   }
   return 0;
}

private String name;
private double salary;
}

/*
输出结果如下:
name=GOGO dustman, salary=4000.0
name=Harry Hacker, salary=35000.0
name=Tony Tester, salary=38000.0
name=Carl Cracker, salary=75000.0
name=Owen Leader, salary=95000.0
1
2
3
4
5
6
7
8
*/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值