Collections.sort没有排序任何东西

Ber*_*sen 8 java sorting collections

我正在尝试以简短的方式对String数组进行排序.我正在尝试使用Collections.sort,但我不明白为什么它不排序任何东西.码:

public static String[] FishNamesSorted;
.....
List<String> nameslist = new ArrayList<String>();
nameslist.toArray(FishNamesSorted);
Collections.sort(nameslist, String.CASE_INSENSITIVE_ORDER); <--- NOT WORKING

Collections.sort(nameslist, new Comparator<String>() { <--- NOT WORKING
    @Override
    public int compare(String p1, String p2) {
    if (p1 == null) {
        return 1;
    }
    if (p2 == null) {
        return -1;
    }
    return p1.compareToIgnoreCase(p2);
    }
});
Run Code Online (Sandbox Code Playgroud)

结果在两种情况下:

  • Poecilia Latipinna
  • Poecilia Reticulata
  • Notropis Chrosomus
  • Pseudomugil Gertrudae
  • ....

Whyyyy?

jmc*_*mcg 5

Collections.sort(list)绝对有效.代码中的问题是您在排序之前将列表放入数组中.如果在将列表放入数组之前先对列表进行排序,则应对数组进行排序

List<String> nameslist = new ArrayList<String>();

/* add elements to namesList */

Collections.sort(nameslist);
Object[] fishNamesSorted = nameslist.toArray();
Run Code Online (Sandbox Code Playgroud)


Ber*_*sen 2

解决方案是

Arrays.sort(FishNamesSorted, String.CASE_INSENSITIVE_ORDER)
Run Code Online (Sandbox Code Playgroud)

我误解了它是如何工作的