在2d数组中对字符串和int进行排序

时间:2015-02-05 02:51:25

标签: java

我有一个二维数组

String[][] Red= {
        {" B"," A","C","E","F","D","J"},
        {"5", " 3","9","10","1","2","4"}
                     };

我想对数组中的数字进行排序。我可以设法对字母进行排序,但不能对数字进行排序吗? 这是我目前的代码

public static void ArrayCreator() {

        String[][] Red = {
            {" B", " A", "C", "E", "F", "D", "J"},
            {"5", " 3", "9", "10", "1", "2", "4"}
        };  
        DayTwoAssingment.ArraySorter(Red);
    }

    public static void ArraySorter(String[][] Green) {
        String[][] Blue = Green;
        for (int i = 0; i < Blue.length; i++) {
            Arrays.sort(Blue[i]);
        }
        System.out.println(Arrays.deepToString(Blue));
    }

2 个答案:

答案 0 :(得分:0)

我认为问题在于你期望&#34;数字&#34;在数组中,当实际上它们是字符串时,它们将被整理为整数。如果你这样做:

String[] numbers = {"5", " 3","9","10","1","2","4"};
Arrays.sort(numbers);
for (String s : numbers) {
    System.out.println(s);
}

你得到:

 3
1
10
2
4
5
9

这是正确的,因为你正在排序字符串。

如果要将它们排序为整数,可以创建两个数组,而不是一个:

String[] letters = {" B"," A","C","E","F","D","J"};
Integer[] numbers = {5, 3, 9, 10, 1, 2, 4};

对这些进行排序可以获得您想要的结果。

另一方面,如果你绝对需要在同一个数组中保留整数和字符串,你可以这样做:

Object[][] red = {{" B"," A","C","E","F","D","J"},
                  {5, 3, 9, 10, 1, 2, 4}};

这样,当您使用循环进行排序时,您将获得第二个数组的元素作为整数排序。这解决了这个问题,虽然我不认为使用Object数组并混合使用类似这样的优秀做法。

答案 1 :(得分:0)

使用自定义Comparator。此外,3之前的空格会导致问题,因此我将其删除:

String[][] Red = { { " B", " A", "C", "E", "F", "D", "J" },
                   { "5", " 3", "9", "10", "1", "2", "4" } };

for (int i = 0; i < Red.length; i++) {
    Arrays.sort(Red[i], new Comparator<String>() {
        public int compare(String s1, String s2) {
            try {
                return Integer.valueOf(s1.trim()).compareTo(Integer.valueOf(s2.trim()));
            }catch(NumberFormatException e) {
                return s1.compareTo(s2);
            }                   
        }
    });
}

System.out.println(Arrays.deepToString(Red));

输出结果为:

  

[[A,B,C,D,E,F,J],[1,2,3,4,5,9,10]]