使用 Collections.sort 对自定义类数组列表字符串进行排序 [英] Sorting custom class array-list string using Collections.sort

查看:34
本文介绍了使用 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.

我的代码是

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;
            }
        }
    });

结果没有排序.

推荐答案

就像 Adam 说的,简单地做:

Like Adam says, simply do:

Collections.sort(
  arrlstContacts, 
  new Comparator<Contacts>() 
  {
    public int compare(Contacts lhs, Contacts rhs) 
    {
      return lhs.Name.compareTo(rhs.Name);
    }
  }
);

方法String.compareTo 执行您的原始代码否定的字典顺序比较.例如,字符串 number1number123 在比较时将分别产生 -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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆