【问题标题】:Collections sort not working properly集合排序无法正常工作
【发布时间】:2013-11-05 11:42:36
【问题描述】:

我是 Java 新手。我正在尝试将文本文件中的几个单词添加到我现有的基于文本的单词列表中。我有下面的代码做

  1. 将文件中的单词添加到现有列表中
  2. 对单词列表进行排序
  3. 将单词保存到文本文件中

"wordList" 是一个包含现有单词的数组列表。

    private void updateDictionaryFile(String filepath) {
    String textCurrentLine = "";

    BufferedReader dictionaryFile = null;
    try {

        Scanner fileScanner = new Scanner(new File(filepath));
        while(fileScanner.hasNextLine()){
            System.out.println("fileScanner.hasNextLine()  "+  fileScanner.hasNextLine());
            textCurrentLine = fileScanner.nextLine();
            if(textCurrentLine.length() > 0)
            if (!wordList.contains(textCurrentLine)) {
                wordList.add(textCurrentLine);
            }
        }

        Collections.sort(wordList);

        String newFile = filepath.replace(".txt", "_new.txt");
        PrintWriter pw = new PrintWriter(new FileOutputStream(newFile));
        for (int i = 0; i < wordList.size(); i++) {
            pw.println(wordList.get(i).toString());
        }
        pw.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (dictionaryFile != null) {
                dictionaryFile.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

新文件中列出的单词未排序。是不是我错过了什么?

下面是输出

A
Achieve
Although
Anything
Ask
Avoid
Badly
Bluma
But
Find
Forget
Goal
Goals
How
In
It
Just
Keep
Know
NOT
Often
Once
One
Psychologists
Reasoning
Reject
Remember
Research
Russian
Shifting
Sidestep
So
Sometimes
Start
Stop
The
This
Those
Under
Visualise
Visualising
We
What
When
With
You
Zeigarnik
a
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
aardvark
aardwolf
aargh
aarrgh
aarrghh
aas

【问题讨论】:

  • 它会改变输出文件中字符串的顺序吗?
  • 我向您保证Collections.sort() 工作正常。
  • 输入和输出文件内容的示例会有所帮助。
  • @JamesShaji 对问题投反对票主要用于鼓励用户改进问题。它们表明访问者认为问题没有包含足够有用的信息来回答问题。在这种情况下,27 分钟后,您仍然没有显示人们认为可能与您的问题相关的 wordList 的确切定义。仅在 27 分钟后,您才添加了输出,这表明 ByteCode 在您提出问题后 13 分钟发布的答案一直都是正确的...
  • @JamesShaji 这就是 cmets 的用途,在这种情况下,问题的不同弱点都很快被指出。我相信你的下一个问题会更好:)

标签: java sorting collections


【解决方案1】:

Collections.sort(wordList); 将完美运行。如果需要忽略大小写,请使用以下代码。

Collections.sort(wordList,String.CASE_INSENSITIVE_ORDER);

【讨论】:

  • 感谢字节码的解决方案。与 flex 和 actionscript 相比,Java 对我来说有点奇怪。
猜你喜欢
  • 1970-01-01
  • 2023-03-22
  • 2013-09-17
  • 1970-01-01
  • 2020-12-14
  • 2012-03-29
  • 2018-07-18
  • 1970-01-01
  • 2013-03-14
相关资源
最近更新 更多