Java和数组操作

时间:2011-12-10 13:42:09

标签: java arrays sorting

我在java中遇到数组问题。 我有一个数组:

double[][] tab2 = {{318, 0.0825},
                  {321, 0.1131},
                  {309, 0.0283},
                  {319, 0.0830}};

我需要将该数组更改为:

double[][] tab2 = {{318, 0.0830},
                  {321, 0.0283},
                  {309, 0.1131},
                  {319, 0.0825}};

这就是我的意思。我有四个号码。在这个例子中,318,321,309和319.每个数字都与另一个数字相连,如318 - 0.0825,321 - 0.1131等。我需要改变第二个值。当与最大数字连接的数字应与较小的数字连接时。 321 - 0.1131应为321 - 0.0283,318 - 0.00830应为318 - 0.0825。有可能做到这一点吗?

4 个答案:

答案 0 :(得分:4)

如果阵列以换位形式排列,那么这样做会更容易。

double[][] tab3 = {
    {318.0, 321.0, 309.0, 319.0},
    {0.0830, 0.1131, 0.0283, 0.0830}}

然后,您可以按升序对第一个数组(tab3[0])进行排序,然后按降序对第二个数组(tab3[1])进行排序。然后,所有数组索引将排列并匹配最大到最小。 double[0][0]将是最大的,double[1][0]将是最小的,匹配309和0.1131。

double[][] tab3 = {
    {309.0, 318.0, 319.0, 321.0},
    {0.1131, 0.0830, 0.0830, 0.0283}}

答案 1 :(得分:1)

在这种情况下,您可以使用Map,将第一个数字指定为键,将第二个数字指定为值。有关地图的详细信息,请参阅以下文档。

http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

答案 2 :(得分:0)

这可能不是最有效的解决方案,但它会起作用

double[][] tab2 = {{318, 0.0825},
              {321, 0.1131},
              {309, 0.0283},
              {319, 0.0830}};
List<Double> firstEntries = new ArrayList<Double>(  );
List<Double> secondEntries = new ArrayList<Double>(  );
for ( double[] doubles : tab2 ) {
  firstEntries.add( doubles[ 0 ] );
  secondEntries.add( doubles[ 1 ] );
}
Collections.sort( firstEntries );
Collections.sort( secondEntries );
Collections.reverse( secondEntries );
//now the lists contain the entries in the correct order
//if needed, they can be grouped again in an array
for ( int i = 0; i < tab2.length; i++ ) {
  double[] doubles = tab2[ i ];
  doubles[1] = secondEntries.get( firstEntries.indexOf( doubles[0] ) );
}

答案 3 :(得分:0)

您可以通过以下方式实现这一目标:

HashMap<Integer,Double> mapValues = new HashMap<Integer,Double>();
// Insert keys and values into mapValues
Integer[] keys  = mapValues.KeySet().toArray(new Integer[]{});
Double[] values = mapValues.Values().toArray(new Double[]{});
Arrays.sort(keys,Collections.reverseOrder());
Arrays.sort(values);
HashMap<Integer,Double> resultMap = new HashMap<Integer,Double>();
for(int i=0; i<keys.length; i++){
   resultMap.put(keys[i], values[i]);
}