2013-04-07 159 views
0

這是排序ArrayList的正確方法嗎? 問題是該列表未被排序。這是正確的排序方法嗎?

out = new StringTokenizer(input.toString()); 
n = (out.countTokens()); 
for (int i = 0; i < n; i++) { 
    String[] words = { out.nextToken().toString() }; 
    final List<String> wordList = Arrays.asList(words); 
    Collections.sort(wordList); 
    System.out.println(wordList.toString()); 
} 
+2

爲什麼不把這種排序移到循環之外? – Maroun 2013-04-07 13:10:15

+0

@Maroun Maroun By alphabyte – antoxa2584 2013-04-07 13:11:45

回答

3

您的每個words[]陣列由單個串,從你的StringTokenizer的下一個標記而獲得。而且你正按迭代的順序進行迭代。所以是的,你的輸出將不是被排序。我想你想要做這樣的事情:

out = new StringTokenizer(input.toString()); 
int count = out.countTokens(): 
List<String> wordList = new ArrayList<String>(count); 
for(int i = 0; i < count; i++) { 
    wordList.add(out.nextToken()); 
} 
Collections.sort(wordList); 

,不使用標記生成器類,它的遺產。以下代碼將爲您提供更好的服務:

List<String> wordList = Arrays.asList(input.split("\\s")); 
Collections.sort(wordList); 
+0

你能告訴我,如何解決它? – antoxa2584 2013-04-07 13:12:03

+0

@ antoxa2584 - 我在編輯代碼。查看更新的答案。 – Perception 2013-04-07 13:15:51

+0

如果我需要用第二個字符對它進行排序,對於examlpe,我該怎麼做? – antoxa2584 2013-04-07 13:19:08

0

out.nextToken().toString()給你一個字符串。我猜想你的數組長度應該是1。 即使你把它放到一個循環中,你也要在每個循環中排序,你必須在循環外進行排序。

StringTokenizer out = new StringTokenizer(input.toString()); 
List<String> wordList = new ArrayList<String>(); 
while(out.hasMoreTokens()) { 
    wordList.add(out.nextToken()); 
} 
Collections.sort(wordList); 
System.out.println(wordList.toString()); 
相關問題