在不涉及任何复杂方法的情况下对 ArrayList 进行排序的最简单方法是什么:
ArrayList<String> myList = new ArrayList<String>();
myList.add("1");
myList.add("2");
myList.add("3");
myList.add("4");
我想要一种Comparator
方式的替代方法,因为这会让事情变得复杂。
想要按字符串升序对列表进行排序,如下所示:
忽略字符串中包含字母的事实,假设我只有数字: 如果按升序排序,我希望 myList 打印出以下内容:
因此,如果我的列表中有以下元素:[1, 2, 3, 4, 12, 100, 40, 50](正如我放入的那样)
使用 Collections.sort(myList)
后,我得到的输出为 [1, 100, 12, 2, 3, 4, 40, 50]
这不是我想要的,我希望输出按数字顺序排列,例如 [1,2,3,4,12,40,50,100] 从最小到最大
最佳答案
您可以使用 Collections.sort(List<T> list)
为此:
Collections.sort(myList);
javadoc 的摘录:
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
关于java - 对字符串 ArrayList 进行排序的最简单方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598856/