由於信息不夠清楚,我一般會回答,您可以應用此到你的情況。 讓我們假設你有一個類人:
public class Person implements Comparable<Person>{
//constructor
String name;
int age;
public String getName()
{
...
}
Public int getAge()
{
...
}
}
爲了比較已創建的對象(因此目前還不清楚哪個參數的對象應該通過比較),你需要創建一個比較! 這個比較器將按年齡先排序,然後按名稱排序。當然,你可以根據你的需要來改變它(或者添加更多的變量來排序)。
靜態類PersonComparator實現比較
public int compare(Person p1, Person p2) {
int ans;
Integer age1 = p1.getAge();
Integer age2 = p2.getAge();
ans = age1.compareTo(age2);
if(ans!=0) //0 means they're equal
return ans;
else
{
String name1; = p1.getName();
String name2; = p2.getName();
return name1.CompareTo(name2);
}
您的排序函數看起來是這樣的:
public void order(List<Person> persons)
{
PersonComparator pc = new PersonComparator()
Collections.sort(persons,pc);
}
名單的人將首先按年齡進行排序,然後按名稱。
- 排序方法在內部使用ASCII值對元素進行排序,因此您需要確保名稱以大寫字母開頭。
整數/字符串的compareTo信息here collection.sort信息here - 這隻要你給它來比較
你的問題不清楚的工具做艱苦的工作適合你。您的解決方案很可能是「爲您的數據創建一個自定義類,並使其實現Comparable,這將在使用Collections.sort()時執行您需要的排序」 – amit
要麼創建一個封裝所有這些數據的Person類並使其實現Comparable或使用自定義比較器。你可能想從[本教程]開始(http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/)。 –
「我在互聯網上做了很多搜索來製作排序算法」:我不相信你。單是這個網站上就有很多類似的問題。 – Raedwald