1. 程式人生 > >陣列排序 java.util.Arrays類的sort方法

陣列排序 java.util.Arrays類的sort方法

陣列排序:

java.util.Arrays類的sort方法可以對 基本型別陣列 和 Comparable型別陣列進行排序. java2核心技術裡沒提到可以對基本型別排序,今天特試了一下. 支援的, 記錄一下.

import java.util.*;
public class EmployeeSortTest
{
public static void main(String[] args)
{
   Employee[] staff=new Employee[3];
   staff[0]=new Employee("Harry Hacker",35000);
   staff[1]=new Employee("Carl Cracker",75000);
   staff[2]=new Employee("Tony Tester",38000);
   Arrays.sort(staff);
   for(Employee e:staff)
   {
    System.out.println("name="+e.getName()+",salary="+e.getSalary());
   }
   int[] array=new int[]{ 86, 88, 68 };
   Arrays.sort(array);
   for(int i:array)
   {
    System.out.println(i);
   }
}
}
// jdk5+ 支援泛型

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 void raiseSalary(double byPercent)
{
   double raise=salary*byPercent/100;
   salary+=raise;
}
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;
}
//Jdk5.0以下

class Employee implements Comparable
{
public Employee(String n,double s)
{
   name=n;
   salary=s;
}
public String getName()
{
   return name;
}
public double getSalary()
{
   return salary;
}
public void raiseSalary(double byPercent)
{
   double raise=salary*byPercent/100;
   salary+=raise;
}
public int compareTo(Object other)
{
   if(salary<((Employee)other).salary)
   {
    return -1;
   }
   if(salary>((Employee)other).salary)
   {
    return 1;
   }
   return 0;
}
private String name;
private double salary;
}