在 Java 中初始化数组的列
Initialize the Columns of an Array in Java
我组合了三个长度相等的数组(稍后我将在 c 列对它们进行排序):
double abc[][] = {
Arrays.copyOf(a, a.length),
Arrays.copyOf(b, a.length),
Arrays.copyOf(c, a.length)
};
当我打电话时
System.out.println(Arrays.deepToString(abc));
我收到:
[[4.0, 2.0, 1.3333333333333333, 5.0, 2.5, 1.6666666666666667 ....
不过,我更喜欢这样的东西:
[[1.0, 1.0, 4.0], [2.0, 2.0, 5.0], [3.0, 3.0, 7.0]]
这可以使用双背心
double test[][] = {{1,1,4},{2,2,5},{3,3,7}};
如何使用三个 double[ ] populate/initialize 三列?
编辑:
基于vojta回答的解决方案:
double abcT[][] = new double[abc[0].length][abc.length];
for (int i = 0; i < abc.length; i++) {
for (int j = 0; j < abc[0].length; j++) {
abcT[j][i] = abc[i][j];
}
}
System.out.println(Arrays.deepToString(abcT));
不幸的是,我认为您的问题没有单线解决方案。您将不得不使用一些自制代码:
static <T> T[][] createMatrix(T[]... columns) {
if (columns== null || columns.length == 0)
return new T[0][0];
int wid = columns.length;
int ht = columns[0].length;
T[][] result = new T[ht][wid];
for (int x = 0; x < wid; x++) {
for (int y = 0; y < ht; y++) {
result[y][x] = columns[x][y];
}
}
return result;
}
希望有用。
我终于找到了这个更优雅的解决方案:
for (int i = 0; i < a.length; i++){
abc[0][i] = a[i];
abc[1][i] = b[i];
abc[2][i] = c[i];
}
虽然这不是 n[] 的通用解决方案,但这避免了制作原始数组的中间副本的需要。然后我只是交换行和列的 for 循环:
for (int j = 0; j < abc[0].length; j++) {
for (int i = 0; i < abc.length; i++) {
System.out.print(abc[i][j] + " ");
}
System.out.print("\n");
}
注意:此解决方案不以预期的 R:C 格式存储,而是以 C:R.
格式检索
我组合了三个长度相等的数组(稍后我将在 c 列对它们进行排序):
double abc[][] = {
Arrays.copyOf(a, a.length),
Arrays.copyOf(b, a.length),
Arrays.copyOf(c, a.length)
};
当我打电话时
System.out.println(Arrays.deepToString(abc));
我收到:
[[4.0, 2.0, 1.3333333333333333, 5.0, 2.5, 1.6666666666666667 ....
不过,我更喜欢这样的东西:
[[1.0, 1.0, 4.0], [2.0, 2.0, 5.0], [3.0, 3.0, 7.0]]
这可以使用双背心
double test[][] = {{1,1,4},{2,2,5},{3,3,7}};
如何使用三个 double[ ] populate/initialize 三列?
编辑:
基于vojta回答的解决方案:
double abcT[][] = new double[abc[0].length][abc.length];
for (int i = 0; i < abc.length; i++) {
for (int j = 0; j < abc[0].length; j++) {
abcT[j][i] = abc[i][j];
}
}
System.out.println(Arrays.deepToString(abcT));
不幸的是,我认为您的问题没有单线解决方案。您将不得不使用一些自制代码:
static <T> T[][] createMatrix(T[]... columns) {
if (columns== null || columns.length == 0)
return new T[0][0];
int wid = columns.length;
int ht = columns[0].length;
T[][] result = new T[ht][wid];
for (int x = 0; x < wid; x++) {
for (int y = 0; y < ht; y++) {
result[y][x] = columns[x][y];
}
}
return result;
}
希望有用。
我终于找到了这个更优雅的解决方案:
for (int i = 0; i < a.length; i++){
abc[0][i] = a[i];
abc[1][i] = b[i];
abc[2][i] = c[i];
}
虽然这不是 n[] 的通用解决方案,但这避免了制作原始数组的中间副本的需要。然后我只是交换行和列的 for 循环:
for (int j = 0; j < abc[0].length; j++) {
for (int i = 0; i < abc.length; i++) {
System.out.print(abc[i][j] + " ");
}
System.out.print("\n");
}
注意:此解决方案不以预期的 R:C 格式存储,而是以 C:R.
格式检索