问题描述
我知道 Collections.sort(myArrayList)
可以在字符串时按字母顺序对数组列表排序,但是当它们是更复杂的数据对象时,两个或多个变量,包括 String
。是否有办法对它们进行排序?
I know that Collections.sort(myArrayList)
can sort an arraylist alphabetically when they are strings, but what about when they are something more complex such as a data object containing two or more variables including a String
. Is there a way to sort them then?
如果没有办法用 Collections
使用for循环或标准排序算法来查看每个对象的字符串变量并在数组中移动对象的索引。
If there isn't a way with Collections
then I can imagine making a for loop or standard sorting algorithm to look at the strings variable of each object and move the object's index in the array.
但我想知道主要是否忽略了集合
方法
But I was wondering mainly if I overlooked something about the Collections
methods
推荐答案
使用。
传递Comparator的实例以根据您的需要进行排序。请注意,的javadoc包含有关构建
Il allows you to pass an instance of Comparator to sort according to your needs. Note that the javadoc of Comparator contains guidelines regarding the building of comparators.
如果比较器仅在本地使用,您可以将其定义为匿名类。下面是一个示例,其中我对对象关于其中一个字段排序是一个字符串:
You may define the comparator as an anonymous class if it's only locally used. Here's an example where I sort objects regarding to one of their fields which is a String :
Collections.sort(groupResults, new Comparator<ProductSearchResult>() {
public int compare(ProductSearchResult result1, ProductSearchResult result2) {
return result1.product.getRsId().compareTo(result2.product.getRsId());
}
});
或者,您也可以让类实现界面,但这只有在您可以定义自然(明显)顺序时才有意义。
Alternatively, you might also make your class implement the Comparable interface but this makes sense only if you can define a natural (obvious) order.
这篇关于按字母顺序排序复杂对象的数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!