[英]How should I sort an ArrayList by some integers contained in it?
顯然這不是我的工作,而是一個例子。 我已經使用Comparable,compareTo,compare,Collections,sort等進行了兩個多小時的工作。這不涉及對其進行排序附加在其上的字符串,但是第一個數字應堅持其各自的詞。 ArrayList必須保持原樣,但就我所知,我已經用盡了所有其他可能性。
6 Worda
8 Wordb
7 Wordc
20 Wordd
2 Worde
5 Wordf
1 Wordg
10 Wordh
1 Wordi
2 Wordj
新的ArrayList類似於:
1 Wordi
1 Wordg
2 Wordj
2 Worde
5 Wordf
6 Worda
8 Wordb
7 Wordc
10 Wordh
20 Wordd
Comparable<MyClass>
compareTo(...)
方法 你說
顯然這不是我的工作,而是一個例子。
如果您需要更多特定的幫助,請考慮發布您的實際代碼以及應該保留的實際數據。
編輯您的帖子:
public int compareTo(Team o) {
if (this.apps >= o.apps) {
return this.apps;
} else {
return o.apps;
}
}
請解釋一下。
例如
// assuming Team has an int field, score and a String field, name
public int compareTo(Team o) {
if (Integer.compare(score, o.score) != 0) {
// the scores are not the same, so return the comparison
return Integer.compare(score, o.score)
} else {
// the scores are the same, so compare the Strings:
return name.compareTo(o.name);
}
}
除了@Hovercraft答案以外,另一種排序方式是。 無需定義自然排序 (使用Comparable),而是創建自己的排序策略(使用Comparator)。
創建一個保存數據的類
public class MyClass{
private String s;
private Integer id;
public static final Comparator MY_COMPARATOR = new MyComparator();
public MyClass(String s, Integer id){
this.s=s;
this.id=id;
}
@Override
public String toString(){
return "ID :"+id+" property: "+s;
}
//Add getter&setter if you need
//static nested class
private static class MyComparator implements Comparator<MyClass>{
@Override
public int compareTo(MyClass c, MyClass c2){
//check possible nullPointerException
int result = c.id.compareTo(c2.id);
if(result == 0){
return c.s.compareTo(c2.s);
}
return result;
}
}
}
然后在客戶端代碼中
List<MyClass> list = new ArrayList<>();
//add data to the list
//print it before sort
System.out.println(list);
Collections.sort(list,MyClass.MY_COMPARATOR);
//print it after sorting
System.out.println(list);
從您的示例看來,您想要使用以下規則對每個元素進行排序:
所以您的可比對象應該在其中,例如(偽代碼)
if (me (number) < other (number) then me is less than
else if (me (number > other <number the me is greater than
else if (me (word) > other (word) then me is less than
else if (me (word) < other (word) then me is greater than
else me equals other
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.