日期:2014-05-20 浏览次数:20887 次
import java.util.Arrays; import java.util.Random; public class TestSync { public static void main(String args[]) { Emp[] emps = { new Emp(1000), new Emp(2000), new Emp(5000), new Emp(3000), new Emp(4000)}; Arrays.sort(emps); System.out.println(emps); for (Emp e : emps) { System.out.println(e); } } } class Emp implements Comparable { String name; int no = 0; double salary; static int count = 0; Emp(double salary) { this.no = ++count; this.name = makeRandomName(); this.salary = salary; } private String makeRandomName(){//五个随即字符??有的坑爹啊。 int count = 0; StringBuffer sb = new StringBuffer(); while(count++ < 5){ int random = new Random().nextInt(); sb.append((char)(Math.abs(random)%25 + 65)); } return sb.toString(); } @Override public String toString() { return "no = " + no + ",name = " + name + ",salary = " + salary; } public int compareTo(Object o) { if (o instanceof Emp) { Emp e = (Emp) o; if (e.salary > this.salary) { return -1; } if (e.salary < this.salary) { return 1; } } return 0; } }