java 如何在java中对arraylist中的元素进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13852077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort elements inside the arraylist in java?
提问by user1805605
Possible Duplicate:
How to sort an arraylist of objects java?
可能的重复:
如何对对象的数组列表进行排序 java?
I have an arraylist that contains very large details i want to sort the data alphabetically but there is no method in arraylist class for sort. Please Help?
我有一个包含非常大的细节的数组列表,我想按字母顺序对数据进行排序,但是在数组列表类中没有用于排序的方法。请帮忙?
回答by arshajii
Use Collections.sort
, which is able to sort any List
.
使用Collections.sort
,它可以对任何List
.
I'm assuming that you're talking about a list of strings, in which case you can simply call Collections.sort
on your list to sort it alphabetically.
我假设您正在谈论一个字符串列表,在这种情况下,您可以简单地调用Collections.sort
您的列表以按字母顺序对其进行排序。
If you're referring to a list of instances of a class you created with an internal string field then you have two options:
如果您指的是使用内部字符串字段创建的类的实例列表,那么您有两个选择:
Have the class implement the
Comparable
interface, then callCollections.sort
on the list with no arguments other than the list itself.Write a custom
Comparator
that works with your class, and pass an instance of it to thesort
method as a second argument along with your list.
让类实现
Comparable
接口,然后调用Collections.sort
列表,除了列表本身之外没有任何参数。编写一个
Comparator
适用于您的类的自定义,并将它的一个实例sort
作为第二个参数与您的列表一起传递给该方法。
If alphabetical ordering is the 'natural' way in which instances of your class should be ordered, you should probably implement Comparable
. If not, you should probably write a Comparator
.
如果字母顺序是应该对类的实例进行排序的“自然”方式,那么您可能应该实现Comparable
. 如果没有,您可能应该编写一个Comparator
.
回答by OCJP
There is no sort method in arraylist But there is a sort method in Collections as ArrayList comes under the collections tree structure you can use the sort of method in collections.Here is the code Collections.sort(arrayList);
arraylist 中没有 sort 方法但是 Collections 中有一个 sort 方法,因为 ArrayList 属于 collections 树结构下,您可以使用 collections 中的 sort 方法。这是代码 Collections.sort(arrayList);