我一直在网上搜索和尝试,但没有找到解决方案。
我有以下 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/