2013-04-07 185 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());