日期:2014-05-20  浏览次数:20637 次

求救String数组的排序问题
String[] str = new String[]{"19.mp3","1.mp3","2.mp3"};
Arrays.sort(musicName);
排序出来的结果是"1.mp3","19.mp3","2.mp3".
因为"1.mp3"和"19.mp3"只能比较第1位
所以"1.mp3"就比"19.mp3"大;
请高人给写个代码,要让这种类型的可以比较

------解决方案--------------------
Java code

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Temp
{
    public static void main(String args[])
    {
        String[] str = new String[]{"19.mp3","1.mp3","2.mp3"}; 
        
        for(Object s: sort(str))
        {
            System.out.println(s);
        }
    }
    
    public static String[] sort(String[] strs)
    {
        String[] ret = new String[strs.length];
        List<String> list = new ArrayList<String>();
        
        for(String str: strs)
        {
            list.add(str);
        }
        
        Collections.sort(list, new CustomComparator());
        
        for(int i = 0; i < list.size(); i++)
        {
            ret[i] = list.get(i);
        }
        
        return ret;
    }
}
class CustomComparator implements Comparator<String>
{
    public int compare(String str1, String str2)
    {
        int name1 = Integer.parseInt(str1.substring(0, str1.indexOf(".")));
        int name2 = Integer.parseInt(str2.substring(0, str2.indexOf(".")));
        return name1 - name2;
    }
}