通过对象属性排序对象的ArrayList [英] Sorting ArrayList of Objects by Object attribute
问题描述
我有对象的ArrayList。这些对象有一个属性或数据类型 - 字符串''。
我需要按该字符串ArrayList中。如何实现这一目标?
I am having an Arraylist of Objects. Those object have an attribute or datatype - 'String'. I need to sort the Arraylist by that string. How to achieve this?
推荐答案
您需要编写一个<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Comparator.html\"><$c$c>Comparator<MyObject>$c$c>并使用<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29\"><$c$c>Collections.sort(List<T>,比较&LT ;?超级T&GT; 整理你的列表
否则,你的为MyObject
还可以的 实现可比&LT;&MyObject的GT;
,定义的自然排序的,用于比较您的具体属性,然后使用<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29\"><$c$c>Collections.sort(List<T>$c$c>来代替。
Or else, your MyObject
can also implements Comparable<MyObject>
, defining a natural ordering that compares on your specific attribute, and then use Collections.sort(List<T>
instead.
- Java Tutorials/Object Ordering
在分拣列表
不同的标准:
- Sorting an ArrayList of Contacts
在比较
和可比
- When to use Comparable vs Comparator
- difference between compare() and compareTo()
- Comparable and Comparator contract with regards to null
- Why does the Java Collections Framework offer two different ways to sort?
这篇关于通过对象属性排序对象的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!