[英]Sort strings by index number of word (the number is given as an argument) in java
例如,如果我確定需要按第二個單詞排序。 我可以這樣創建比較器。
class SecondWordComparator implements Comparator<String>
{
@Override
public int compare(String s1, String s2)
{
String[] a1 = s1.split(" ");
String[] a2 = s2.split(" ");
return a1[1].compareTo(a2[1]);
}
}
是否可以通過參數將另一個單詞的索引號提供給Comparator?
不通過Comparator
的參數(參數) ,否,但是您可以:
使它成為您的Comparator
具體課程的一個領域,或
如果將Comparator
實現為匿名類,則它可以是final
變量或參數,實現將關閉
#1相當瑣碎。 這是#2( 實時復制 )的示例:
import java.util.*;
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
String[] strings = new String[] {
"one two three",
"uno due tre",
"uno dos tres",
"un deux trois"
};
sort(strings, 2); // 2 = third word
for (String s : strings) {
System.out.println(s);
}
}
private static void sort(String[] strings, final int index) {
Arrays.sort(strings, new Comparator<String>() {
@Override
public int compare(String s1, String s2)
{
String[] a1 = s1.split(" ");
String[] a2 = s2.split(" ");
String word1 = a1.length > index ? a1[index] : "";
String word2 = a2.length > index ? a2[index] : "";
return word1.compareTo(word2);
}
});
}
}
由於您要從接口覆蓋方法
@Override
public int compare(String s1, String s2)
然后在方法簽名中添加參數會違反接口中的聲明方法...。
所以不可能...
Java是一種非常靈活的語言,因此您始終可以實現比較器的匿名實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.