动态数组排序:
Listls=new ArrayList (); ls.add(-1); ls.add(11); ls.add(100); ls.add(8); ls.add(2); ls.add(10); Collections.sort(ls);// 升序排列 System.out.print("排序后结果是:"); for(int i:ls){ System.out.print(i+","); } System.out.println(); Collections.reverse(ls);// 颠倒 System.out.print("颠倒后结果是:"); for(int i:ls){ System.out.print(i+","); }
自定义排序规则的例子:
public class Emp implements Comparable{ private int age; private int salary; private String name; public Emp(String name,int age,int salary){ this.name=name; this.age=age; this.salary=salary; } public String toString(){ StringBuilder sb=new StringBuilder(); sb.append("姓名:"+name); sb.append(" 年龄:"+age); sb.append(" 薪水:"+salary); return sb.toString(); } @Override public int compareTo(Object o) { Emp another = (Emp) o; return this.name.compareTo(another.name); /*if(this.salary!=another.salary){ return this.salary-another.salary; }else{ return this.age-another.age; }*/ } public static void main(String[] args){ Listls=new ArrayList (); ls.add(new Emp("Andy",20,4500)); ls.add(new Emp("Cdins",30,10000)); ls.add(new Emp("Douasa",40,30000)); ls.add(new Emp("cahsa",20,5000)); ls.add(new Emp("Hewqw",30,15000)); ls.add(new Emp("Xawew",60,30000)); ls.add(new Emp("Baod",30,30000)); Collections.sort(ls);// 按compareTo中规则排列 System.out.println("排序后结果是:"); for(Emp i:ls){ System.out.println(i.toString()); } }}
将员工信息写入文件的类
public class WriteSample{ public static void main(String[] args){ try { BufferedWriter out = new BufferedWriter(new FileWriter("c://write.txt")); out.write("张三 23 男 3500\r\n"); out.write("李四 24 女 13500\r\n"); out.write("王五 25 男 1500\r\n"); out.write("赵六 93 女 1300"); out.close(); } catch (IOException e) { e.printStackTrace(); } }}
将员工信息读出文件并进行排序的类
import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import java.util.List;class Emp implements Comparable{ String name; int age; String sex; int salary; public Emp(String line){ String[] arr=line.split(" "); name=arr[0]; age=Integer.parseInt(arr[1]); sex=arr[2]; salary=Integer.parseInt(arr[3]); } public String toString(){ StringBuilder sb=new StringBuilder(); sb.append("姓名:"+name); sb.append(" 年龄:"+age); sb.append(" 性别:"+sex); sb.append(" 薪水:"+salary); return sb.toString(); } @Override public int compareTo(Object o) { Emp another = (Emp) o; return this.salary-another.salary;//this.name.compareTo(another.name); /*if(this.salary!=another.salary){ return this.salary-another.salary; }else{ return this.age-another.age; }*/ }}public class ReadSample{ public static void main(String[] args){ try { Listls=new ArrayList (); BufferedReader in = new BufferedReader(new FileReader("c://write.txt")); String str; while ((str = in.readLine()) != null) { ls.add(new Emp(str)); } in.close(); Collections.sort(ls); for(Emp e:ls){ System.out.println(e); } } catch (IOException e) { } }}