android - 为什么我的 ArrayList<String> 排序不正确?

标签 android sorting arraylist android-sqlite comparator

我一直在网上搜索和尝试,但没有找到解决方案。

我有以下 ArrayList:

{ Cate1, Cate3, Cate6, Cate2, ...., through Cate10}

我尝试了以下解决方案:

public ArrayList<String> GetAllCategories_ByAscOrder() {
    db = getWritableDatabase();

    ArrayList<String> Category_ArrayList = new ArrayList<String>();

    Cursor cursor = db.query(Category_TABLE, null, null, null, null, null, Category_List + " ASC");

    if(cursor != null)
    {
        while(cursor.moveToNext())
        {
            String CATEGORY = cursor.getString(cursor.getColumnIndex(Category_List));
            Category_ArrayList.add(CATEGORY);
        }
    }

    cursor.close();
    return Category_ArrayList;
}

还有这些:

Collections.sort(CATEGORY_LIST, new Comparator<String>(){
    public int compare(String obj1, String obj2)
        {
           return obj1.compareToIgnoreCase(obj2);
        }
    });
}

//OR THIS:

Collections.sort(CATEGORY_LIST, new Comparator<String>(){
    public int compare(String obj1, String obj2)
        {
           return obj1.compareTo(obj2);
        }
    });
}


//OR THIS:

Collections.sort(CATEGORY_LIST, String.CASE_INSENSITIVE_ORDER);

但所有这些都给了我相同的排序结果: Cate1、Cart10、Cate2、Cate3 等... Cate9

我希望排序后的列表是这样的:

类别 1 到类别 10

有人可以指导我如何实现这一目标吗?

非常感谢

编辑:

我忘了说我让用户自由命名他们的类别名称。

最佳答案

这样做:

          Collections.sort(list , new Comparator<String>(){
              public int compare( String a, String b ){
                  // if contains number
                  if( a.substring(4).matches("\\d+") && b.substring(4).matches("\\d+")) {
                      return new Integer( a.substring(4) ) - new Integer( b.substring(4) );
                  }
                  // else, compare normally. 
                  return a.compareTo( b );
              }
          });

关于android - 为什么我的 ArrayList<String> 排序不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26204972/

相关文章:

algorithm - 在表中查找排序顺序

android - 是否可以使用 MockK 监视挂起的 Android Room DAO 功能

Android 从 url 下载并显示 pdf

android - 如何选择FragmentPagerAdapter的中间页?

android - Facebook 帐户套件在某些设备上崩溃

java - 如何查找数组列表中不同项目的总数。

java - 通过希尔排序对字符串行进行排序

用于将 boolean 列排序为 true、null、false 的 SQL

java - HashMap 和 List 中的相似元素

java - while 循环之外的 ArrayList 未更新