2012-03-15 89 views
0

我有一个关于排序的问题。如何对二维数组进行排序?

int[][] array = {{4,2},{1,7},{4,5},{1,2},{1,1},{4,1}}; 

对这个数组进行排序后,会变得如下图所示。

int[][] array = {{1,1},{1,2},{1,7},{4,1},{4,2},{4,5}}; 

我倒感到困惑的是,如果我在第一次对行进行排序和执行上,在第二列的排序,我怎么会改变两人在同一时间的价值的时候我排序的行和列。

回答

0

看到这个例子...

Sort a two dimensional array based on one column 
The first column is a date of format "yyyy.MM.dd HH:mm" and the second column is a String. 

既然你说的2-d阵列,我认为 “格式的日期......” 是指一个字符串。这是用于排序String [] []的二维数组的代码:

import java.util.Arrays; import java.util.Comparator;

public class Asdf { 

public static void main(final String[] args) { 
    final String[][] data = new String[][] { 
      new String[] { "2009.07.25 20:24", "Message A" }, 
      new String[] { "2009.07.25 20:17", "Message G" }, 
      new String[] { "2009.07.25 20:25", "Message B" }, 
      new String[] { "2009.07.25 20:30", "Message D" }, 
      new String[] { "2009.07.25 20:01", "Message F" }, 
      new String[] { "2009.07.25 21:08", "Message E" }, 
      new String[] { "2009.07.25 19:54", "Message R" } }; 

    Arrays.sort(data, new Comparator<String[]>() { 
     @Override 
     public int compare(final String[] entry1, final String[] entry2) { 
      final String time1 = entry1[0]; 
      final String time2 = entry2[0]; 
      return time1.compareTo(time2); 
     } 
    }); 

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

}

+0

对不起,当我跑这一项,它表明“比较不能被解析为一个类型”和“数组不能得到解决”。这里有什么问题? – 2012-03-15 08:02:01

+0

你需要做... import java.util.Arrays; import java.util.Comparator; – 2012-03-15 08:09:56

+0

非常感谢。尽管我仍然不明白它是如何工作的,但它实际上可以解决我的问题。 :) – 2012-03-15 23:51:36

相关问题