简单类型的排序
简单类型不外是byte, char, short, int, long, float, double等数据类型,这些类型不能放在聚集中,只能使用数组。java.util.Arrays方法提供了对这些类型的sort方法(实际上还有很多其他有用的方法),下面是对一个简单的int数组排序:
int[] arr = { 2, 3, 1, 10, 7, 4 };
System.out.print(“before sort: “);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
Arrays.sort(arr);
System.out.print("after sort: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
输出结果:
before sort: 2 3 1 10 7 4
after sort: 1 2 3 4 7 10
对象的排序
对象可以放在数组里,同样调用Arrays.sort(Object[] arr)即可;也可以放到聚集里,用java.util.Collections的sort(List list)。注意不是list必须实现List接口而不仅仅是Collection接口。
但是这个类必须实现了java.lang.Comparable接口。这个接口只有一个方法:int compartTo(Object o),当本对象比传入的对象大时,返回一个正整数。 以类Programmer为例:
class Programmer implements Comparable
private String name;
private String language;
private double pay;
public Programmer(String name, String language, double pay) {
this.name = name;
this.language = language;
this.pay = pay;
}
public int compareTo(Programmer other) {
return (int) pay – (int) other.pay;
}
public String toString() {
return “{name: ” + name + “, language: ” + language + “, money: ” + pay + “}”;
}
}
对其进行排序:
ArrayList
list.add(new Programmer(“张三”, “C”, 12000));
list.add(new Programmer(“李四”, “Java”, 200));
list.add(new Programmer(“王五”, “C++”, 5000));
list.add(new Programmer(“钱六”, “VB”, 3000));
System.out.println(“before sort: ” + list);
Collections.sort(list);
System.out.println(“after sort: ” + list);
输出:
before sort: [{name: 张三, language: C, money: 12000.0}, {name: 李四, language: Java, money: 200.0}, {name: 王五, language: C++, money: 5000.0}, {name: 钱六, language: VB, money: 3000.0}]
after sort: [{name: 李四, language: Java, money: 200.0}, {name: 钱六, language: VB, money: 3000.0}, {name: 王五, language: C++, money: 5000.0}, {name: 张三, language: C, money: 12000.0}]
[整理自网络]
Sorry, the comment form is closed at this time.
No comments yet.