How can I sort this ArrayList the way that I want?

前端 未结 12 1753
刺人心
刺人心 2020-12-04 18:17

Here is a simple sorting program of an ArrayList:

ArrayList list = new ArrayList();

list.add(\"1_Update\");
list.add(\"11_Add\")         


        
12条回答
  •  不思量自难忘°
    2020-12-04 18:49

    When you sort this type of data as a string, it is comparing the characters themselves, including the digits. All of the string that begin with "1", for example, will end up together. So the order ends up similar to this...

    1 10 100 2 20 200

    At no point does the sort "realize" that you are assigning meaning to subsets of the string, such as the variable length numbers at the front of the string. When sorting numbers as strings, padding to the left with zeros as much as required to cover the largest number can help, but it does not really solve the problem when you don't control the data, as in your example. In that case, the sort would be...

    001 002 010 020 100 200

提交回复
热议问题