1D - > 2D字符串数组转换

时间:2014-11-23 19:36:58

标签: java arrays type-conversion multidimensional-array

是否可以从一维字符串数组中创建一个2D数组,例如3x4 one?例如,

String[] animals = {"Abyssinian", "Beagle", "Bear", "Cassowary", "Chesapeake Bay Retriever", 
                    "Common Buzzard", "Dunker", "Eskimo Dog", "Ferret", 
                    "Glow Worm", "Jellyfish", "Komodo Dragon"};

应转换为String[][]

2 个答案:

答案 0 :(得分:0)

是的,这是可能的。例如(你必须根据你想要达到的确切结果来定制它)

public static String[][] convertTo2D( String[] arr, int x, int y ) {
  //if ( arr.length != x * y ) throw new IllegalArgumentException();
  String[][] ret = new String[x][y];
  for( int i_x = 0, i = 0; i_x < x; i_x++ )
    for( int i_y = 0; i_y < y; i_y++, i++ ) {
      //if ( i >= arr.length ) return ret;
      ret[i_x][i_y] = arr[i];
    }
  return ret;
}

答案 1 :(得分:-1)

这个例子展示了一种从数组中加载矩阵的方法。

String[] animals = {"Abyssinian", "Beagle", "Bear", "Cassowary",
    "Chesapeake Bay Retriever", "Common Buzzard", "Dunker", "Eskimo Dog",
    "Ferret", "Glow Worm", "Jellyfish", "Komodo Dragon"};

int matrix[][] = new String[3][4];
int apos = 0;

for (int x=0; x < 3; x++) {
    for (int y=0; y<4; y++) {
        matrix[x][y] = animals[apos];
        apos = apos + 1;
    }
}

您也可以将动物数组作为矩阵访问,比如说你想要动物[i] [j]你可以使用:

animal[ i*4 + j ]
相关问题