【问题标题】:Taking N number of arrays and turning it into a multidimensional array with N rows JAVA取N个数组并将其变成N行JAVA的多维数组
【发布时间】:2011-04-11 00:05:07
【问题描述】:

我正在尝试编写将 N 个数组转换为具有 N 行的多维数组的代码。我目前有一个代码可以将 2 个数组转换为 2 行的多维数组。但是,我不确定如何修改它以使此代码采用 N 个数组。

此外,我的代码目前只能采用相同大小的数组。但是,它需要能够采用不同长度的数组。这意味着我的多维数组中的行并不总是相等的长度。有人告诉我,这意味着列表可能比数组更合适。但是我对列表不熟悉。

这是我目前的代码:

public class test5 {
    int [][] final23;

public int [][] sum(int [] x, int[] y)
{
final23= new int[2][x.length];
for (int i = 0; i < Math.min(x.length, y.length); i++)
{

    final23 [0][i] = x[i];
    final23 [1][i] = y[i];
}
return final23;
}

public void print()
{
for (int i = 0; i < final23.length; i++)
{
    for (int j = 0; j<final23[0].length; j++)
    {

        System.out.print(final23[i][j]+" ");
    }
    System.out.println();
}
}




public static void main(String[] args)
    {
        int l[] = {7,3,3,4};
        int k[] = {4,6,3};
        test5 X = new test5();

        X.sum(k,l);
        X.print();
    }
}

提前致谢。抱歉,我是 java 新手,刚刚学习。

【问题讨论】:

  • 为什么不学习收藏?这比弄乱固定长度的数组要容易得多

标签: java arrays multidimensional-array arraylist


【解决方案1】:
import java.util.Arrays;
class Arr
{
public static void main(String[] args)
{
 int[][] ar=toMulti(new int[]{1,2},new int[]{1,2,3},new int[]{5,6,7,8});
 System.out.println(Arrays.deepToString(ar));

/*OR You can directly declare 2d array like this if your arrays don't
come as user inputs*/
 int[][] arr={{1,2,3},{1,2},{3,4}};
  System.out.println(Arrays.deepToString(arr));
}    
   /* ... is known as variable argument or ellipsis.
      int[] ... denotes that you can give any number of arguments of the type int[]
      The function input that we get will be in 2d-array int[][].So just return it.*/
   public static int[][] toMulti(int[] ... args) {
    return args;

}
}

【讨论】:

  • 这段代码只是返回二维数组中的引用。但如果你需要它作为副本,那么你最好遵循史蒂夫的代码。不同之处在于,如果你对一维数组进行任何更改,它将反映在2d 数组也是如此,反之亦然。但是如果您正在处理巨大的数组,这将更快并且使用更少的内存。
【解决方案2】:

由于它们的长度可能不相等,您将不得不考虑矩阵上的死点,也许使用Null Object pattern。将每个元素初始化为可以统一处理的特殊情况,就像任何其他元素一样。

顺便说一下,这是我对如何使用数组的建议。 Collections aren't hard 不过。

【讨论】:

    【解决方案3】:

    java 中的多维数组的大小并不相似——它们只是排列在一个数组中的一堆数组,就像任何其他对象一样。如果您希望它们都具有相同的大小,则必须找到最大大小并用某种空值或默认值填充较小的数组。

    无论如何,既然要复制一些N个数组,只要接受不同的长度,为什么不使用可变参数:

    public static int[][] toMulti(int[] ... args) {
     // you can't resize an array, so you have to size your output first:
     int[][] output = new int[args.length][];
     for (int i =0; i<args.length; i++)
     {
        output[i[=args[i].clone();
    
       //you could also do this copying 1 at a time, or with
       int[] arr =new int[args[i].length];
       System.arraycopy(args[i], 0, arr, 0, args[i].length);
       output[i]=arr;
     }
    

    如果您想将它们全部设置为相同的大小 System.arraycopy 会更好,因为您会以最大大小创建数组,剩余的值将自动为 0(或对象数组的空值)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-02
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多