您需要實現可比接口
implements Comparable
該做的工作是
public int compareTo(Object obj)
{
}
請注意,對象往往是取而代之的是一個完整的對類型,因爲一般語法的方法它可以在實現語句中使用(如下所示)。
完整的例子就是here in the tutorial docs希望這有助於
完整的例子(採取從上面的鏈接如下),我剛纔的情況下添加此鏈接出現死在某個時刻
import java.util.*;
public class Name implements Comparable<Name> {
private final String firstName, lastName;
public Name(String firstName, String lastName) {
if (firstName == null || lastName == null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() { return firstName; }
public String lastName() { return lastName; }
public boolean equals(Object o) {
if (o == null || !(o instanceof Name))
return false;
Name n = (Name) o;
return n.firstName.equals(firstName) && n.lastName.equals(lastName);
}
public int hashCode() {
return 31*firstName.hashCode() + lastName.hashCode();
}
public String toString() {
return firstName + " " + lastName;
}
public int compareTo(Name n) {
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
}
}
從文章的客戶端代碼:
import java.util.*;
public class NameSort {
public static void main(String[] args) {
Name nameArray[] = {
new Name("John", "Smith"),
new Name("Karl", "Ng"),
new Name("Jeff", "Smith"),
new Name("Tom", "Rich")
};
List<Name> names = Arrays.asList(nameArray);
Collections.sort(names);
System.out.println(names);
}
}
貴教授想要實現的排序算法自己呢? – 2012-04-13 17:33:41
@joncarl說的是一個好點,如果是的話,你需要查看bubblesort(它相當容易實現,但不是那麼快) – 2012-04-13 17:40:32
是的,我會實現插入排序算法。 – user1253201 2012-04-13 18:24:00