java - 动态添加数组到数组中

标签 java arrays graph

我正在制作一个 array2,即 array2 = {i,j},并且我有另一个二维数组 e_list={} 。现在我想将 array2 追加到 e_list 中。

     int[][] G = {{0, 0, 0, 1, 1}, 
                  {0, 0, 1, 1, 1}, 
                  {0, 1, 0, 0, 0}, 
                  {1, 1, 0, 0, 1}, 
                  {1, 1, 0, 1, 0}, 
                 }; 

     int[][]  e_list = {};  //<-initialize 2D array here

     for (int i=0; i < 5; i++){
         for (int j=0; j < 5; j++){  
             if (G[i][j] == 1){                  
                     int[] array2 = {i,j};
                     System.out.print(array2[1]); 
                     System.out.print(","); 
                     System.out.println(array2[0]);
                     //----------------------------//<-- here I want to add this array2 into that 2D array e_list   

                     //this is one of my failed try;
                     for (int t=1; t <= 6; t++){
                         for (int tt=0; tt < 1; tt++){
                             e_list[t][tt] = array2[tt];
                         }                       
                     }

         }
        }    
       }

现在,代码只是打印 array2 的第一个和第二个索引。但我想要这样的东西; e_list = {{3,0}, {4,0}, ... , {1,2}} 我想访问 e_list,例如 e_list[0][0] = 3、e_list[1][0] = 4 等

我已经尝试过内部的 for 循环...但没有成功。它说“java.lang.ArrayIndexOutOfBoundsException: 0”

最佳答案

您需要实际告诉 e_list 它有多大,然后才能为其赋值。类似 int[][] e_list = new int[5][5];而不是int[][] e_list = {};

否则 e_list 将没有大小,因此一旦您尝试在其中写入内容,您就会遇到数组索引越界异常(您的数组没有大小,但您试图访问其中的内容)

有趣的是,你的//<-initialize 2D array here评论已经准确地说明了您还需要做什么:D 但是仅仅写评论而不是实际做某事是不够的。

关于java - 动态添加数组到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40420463/

相关文章:

java - 运行.jar文件时出现NoClassDefFoundError

传递给函数时更改数组指针的值

arrays - 多个数组中元素的组合

c++ - BGL : adjacency list returns wrong edge property for descriptor

java - 在 Apache CXF JAX-RS 中,如何打开 AUTO_REDIRECT_ALLOW_REL_URI 标志?

java - 如何在 Google App Engine (Java) 中启用 session 支持?

PHP - 如何将数组中的数据显示到树或表中?

python-3.x - 如何将基于 "None"距离的Dijsktra算法的Python实现转换为 "Infinity"距离

graphics - 图形绘制软件

java - JPA Spring 存储库日期过滤返回空数组