Collections.sort()没有按正确的顺序排序

lha*_*ahn 0 java sorting collections

我在Java中有这个代码:

List<String> unSorted = new ArrayList<String>();
List<String> beforeHash = new ArrayList<String>();
String[] unSortedAux, beforeHashAux; 
String line = null;

BufferedReader reader = new BufferedReader(new FileReader("C:\\CPD\\temp0.txt"));
    while ((line = reader.readLine()) != null){
        unSorted.add(line);  
        beforeHash.add(line.split("#")[0]); 

    }
    reader.close();

    Collections.sort(beforeHash);
    beforeHashAux = beforeHash.toArray(new String[beforeHash.size()]);
    unSortedAux = unSorted.toArray(new String[unSorted.size()]);

    System.out.println(Arrays.toString(beforeHashAux));
    System.out.println(Arrays.toString(unSortedAux));
Run Code Online (Sandbox Code Playgroud)

它读取名为temp0.txt的文件,其中包含:

Carlos Magno#261
Mateus Carl#12
Analise Soares#151
Giancarlo Tobias#150
Run Code Online (Sandbox Code Playgroud)

我的目标是在字符串中对名称进行排序,而不是"#"之后的字符串.我正在使用beforeHash.add(line.split("#")[0]); 去做这个.问题是它正确读取文件,但它按错误的顺序排序.相应的产出是:

[Analise Soares, Giancarlo Tobias, Mateus Carl, Carlos Magno]
[Carlos Magno#261, Mateus Carl#12, Analise Soares#151, Giancarlo Tobias#150]
Run Code Online (Sandbox Code Playgroud)

第一个结果是"排序的",注意"Carlos Magno"来自"Mateus Carl".我在代码中找不到问题.

Jon*_*eet 8

问题是"Carlos Magno"以Unicode字节顺序标记开头.

如果你将示例文本([Analise ... Carlos Magno])复制并粘贴到Unicode Explorer中,你会看到就在Carlos Magno的"C"之前,你有U + FEFF.

基本上,你需要在阅读文件时删除它.最简单的方法就是使用:

line = line.replace("\ufeff", "");
Run Code Online (Sandbox Code Playgroud)

...或先检查:

if (line.startsWith("\ufeff")) {
    line = line.substring(1);
}
Run Code Online (Sandbox Code Playgroud)

请注意,您应该在打开文件时确实指定要使用的编码 - 使用FileInputStream包装中的InputStreamReader.

  • +1但是我不愿意点击tinyurl链接...为什么不发布http://csharpindepth.com/Articles/General/Unicode.aspx#explorer的完整链接? (2认同)
  • @Duncan:因为它更容易记住http://tinyurl.com/unicode-explorer,而其他人可能想要自己记住它.如果你愿意,你总是可以使用http://preview.tinyurl.com/unicode-explorer - 但是你不清楚为什么你信任csharpindepth.com而不是tinyurl.com链接...... (2认同)
  • @ user3580294:排序.首先,我使用帖子中的文字重现了问题,然后我开始查看实际包含的数据. (2认同)