将字符串解释为数字时,数组未正确排序

时间:2014-12-29 23:31:17

标签: java arrays sorting

我一直在尝试调整在另一个线程中找到的代码,以便不使用第一个coloumn中的值来比较它使用最后一个存储为字符串的数字。我已经改变了coloumn数字,但它仍然排在第一位。

public class Test {

    public static void main(final String[] args) {
        final String[][] data = new String[][] {
                new String[] { "Adam","3", "12" },
                new String[] { "Sam","5", "22" },
                new String[] { "Joe","2", "3" },
                new String[] { "Ryan","4", "4" },
                new String[] { "Leroy","2", "5" },
                new String[] { "Smith","1", "6" },};

        Arrays.sort(data, new Comparator<String[]>() {
            @Override
            public int compare(final String[] entry1, final String[] entry2) {
                final String St1 = entry1[2];
                final String St2 = entry2[2];
                return St2.compareTo(St1);

            }
        });

        for (final String[] s : data) {
            System.out.println(s[0] + " " + s[1]+ " " + s[2]);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

假设您要对字符串进行数字排序,您必须先将字符串转换为数字,否则数字将按字母顺序排序,即&#34; 2&# 34;将比#&#34; 10&#34;更重要(因为2在ascii之后出现):

public int compare(final String[] entry1, final String[] entry2) {
    String st1 = entry1[2];
    String st2 = entry2[2];
    int n1 = Integer.parseInt(st1);
    int n2 = Integer.parseInt(st2);
    return Integer.compare(n2, n1);
}