排序使用Collections.sort自定义类数组列表字符串 [英] Sorting custom class array-list string using Collections.sort
问题描述
我试图通过宣称自己的匿名比较我的自定义类使用Collections.sort数组列表进行排序。但排序不按预期工作。
I am trying to sort my custom class array-list using Collections.sort by declaring my own anonymous comparator. But the sort is not working as expected.
我的code是
Collections.sort(arrlstContacts, new Comparator<Contacts>() {
public int compare(Contacts lhs, Contacts rhs) {
int result = lhs.Name.compareTo(rhs.Name);
if(result > 0)
{
return 1;
}
else if (result < 0)
{
return -1;
}
else
{
return 0;
}
}
});
结果不按排序顺序。
The result is not in sorted order.
推荐答案
像亚当说,简单地做:
Collections.sort(
arrlstContacts,
new Comparator<Contacts>()
{
public int compare(Contacts lhs, Contacts rhs)
{
return lhs.Name.compareTo(rhs.Name);
}
}
);
该方法<一href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#compareTo%28java.lang.String%29"><$c$c>String.compareTo$c$c>进行逐一比较,你的原来的code被否定。例如字符串数字1
和 number123
时相比会产生-2和2分别。
The method String.compareTo
performs a lexicographical comparison which your original code is negating. For example the strings number1
and number123
when compared would produce -2 and 2 respectively.
通过简单地返回1,0或-1有一个机会(因为正在发生的事情对你而言)合并的合并部分来挑选 Collections.sort
方法无法列表中的产生是不按字母顺序排列的列表的字符串之间充分区分。
By simply returning 1, 0 or -1 there's a chance (as is happening for you) that the merge part of the merge sort used Collections.sort
method is unable to differentiate sufficiently between the strings in the list resulting in a list that isn't alphabetically sorted.
这篇关于排序使用Collections.sort自定义类数组列表字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!