第一个例子
-
- import java.util.Iterator;
-
- import java.util.Set;
- import java.util.TreeSet;
-
- public class SortByValue {
-
- public static void main(String[] args) {
- Set<Pair> set = new TreeSet<Pair>();
- set.add(new Pair("me", "1000"));
- set.add(new Pair("and", "4000"));
- set.add(new Pair("you", "3000"));
- set.add(new Pair("food", "10000"));
- set.add(new Pair("hungry", "5000"));
- set.add(new Pair("later", "6000"));
- set.add(new Pair("myself", "1000"));
- for (Iterator<Pair> i = set.iterator(); i.hasNext();)
-
- System.out.println(i.next());
- }
- }
-
- class Pair implements Comparable<Object> {
- private final String name;
- private final int number;
-
- public Pair(String name, int number) {
- this.name = name;
- this.number = number;
- }
-
- public Pair(String name, String number) throws NumberFormatException {
- this.name = name;
- this.number = Integer.parseInt(number);
- }
-
- public int compareTo(Object o) {
- if (o instanceof Pair) {
-
- int cmp = number - ((Pair) o).number;
- if (cmp != 0) {
- return cmp;
- }
- return name.compareTo(((Pair) o).name);
- }
- throw new ClassCastException("Cannot compare Pair with "
- + o.getClass().getName());
- }
-
- public String toString() {
- return name + ‘ ‘ + number;
- }
- }
- 输出结果:
- me 1000
- myself 1000
- you 3000
- and 4000
- hungry 5000
- later 6000
- food 10000
第二个例子:
- import java.util.*;
-
- public class NameSort {
- public static void main(String[] args) {
- Name[] nameArray = { new Name("John", "Lennon"),
- new Name("Karl", "Marx"), new Name("Groucho", "Marx"),
- new Name("Oscar", "Grouch") };
- Arrays.sort(nameArray); //根据元素的自然顺序对指定对象数组按升序进行排序。数组中的所有元素都必须实现
Comparable
接口。此外,数组中的所有元 //素都必须是可相互比较的(也就是说,对于数组中的任何 e1 和 e2 元素而言,e1.compareTo(e2) 不得抛出 ClassCastException)。
- for (int i = 0; i < nameArray.length; i++) {
- System.out.println(nameArray[i].toString());
- }
- }
- }
-
- class Name implements Comparable<Name> {
- public String firstName, lastName;
-
- public Name(String firstName, String lastName) {
- this.firstName = firstName;
- this.lastName = lastName;
- }
-
- public int compareTo(Name o) {
- int lastCmp = lastName.compareTo(o.lastName);
-
- return (lastCmp == 0 ? firstName.compareTo(o.firstName) : lastCmp);
- }
-
- public String toString() {
- return firstName + " " + lastName;
- }
- }
- 输出结果:
- Oscar Grouch
- John Lennon
- Groucho Marx
- Karl Marx
- public int compareTo(Pair o) {
- int cmp = number - o.number;
- return (cmp == 0 ? name.compareTo(o.name) : cmp);
- }
- ----------------------
- public int compareTo(Name o) {
- int lastCmp = lastName.compareTo(o.lastName);
-
- return (lastCmp == 0 ? firstName.compareTo(o.firstName) : lastCmp);
- }
本文转载至:http://ocaicai.iteye.com/blog/794438
对象排序,compareTo
原文:http://www.cnblogs.com/qjm201000/p/qjm_2.html