简体   繁体   English

初始化二维数组(java)

[英]initialising 2-dimensional array (java)

I am trying to initialise an 2-d array with some objects. 我试图用一些对象初始化一个二维数组。 And I want the 2nd "dimension" to have arrays of different sizes eg different powers of to. 我希望第二个“维度”具有不同大小的数组,例如to的不同幂。 And my idea is the following code: 我的想法是以下代码:

NodeMatrix=new BNode[n][];
    for(int i=0;i<n;i++) {
        for(int j=0;j<Math.pow(2,i);j++) {
            NodeMatrix[i]=new BNode[(int)Math.pow(2,i)];
            NodeMatrix[i][j]= new BNode(i);
        }

but it doesnt work and I have now other idea how it could be done. 但它不起作用,我现在又有其他想法可以做到。

I didn't understood your requirement completely. 我不完全了解您的要求。 But the below code may help you to understand the 2D arrays in Java. 但是下面的代码可以帮助您了解Java中的2D数组。

public static void generateDynamicArray() {
        int[][] arr = new int[5][];

        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[(int)Math.pow(2, i)];
        }


        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = (int) (Math.random() * 10);
            }
        }


        for(int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] +" ");
            }
            System.out.println();
        }
    }

You have to initialize BNode array before you iterate over it. 您必须在对其进行迭代之前初始化BNode数组。 As an advice, consider if you really want to set length by powers of two, that will grow fast. 作为建议,请考虑一下,如果您真的想将长度设置为2的幂,则长度会快速增长。

NodeMatrix=new BNode[n][];
for(int i=0;i<n;i++) {
    NodeMatrix[i]=new BNode[(int)Math.pow(2,i)];
    for(int j=0; j < NodeMatrix[i].length; j++) {  
        NodeMatrix[i][j]= new BNode(i);
    }
}

Basically, It cannot be done in java. 基本上,它不能在Java中完成。 2 d array is nothing but just array of arrays. 2维数组不过是数组数组而已。

One option can be use a list of arrays. 一种选择是使用数组列表。

Example: 例:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JavaArrayListOfStringArray {

    public static void main(String[] args) {

        List <String[]> list = new ArrayList <String[]>();

        String [] arr1 = {"a","b","c"};
        String [] arr2 = {"1","2","3"};

        list.add(arr1);
        list.add(arr2);

        for(String[] arr : list) {
            System.out.println(Arrays.toString(arr));
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM