如何在Java中为已初始化的对象[] []添加新值?

时间:2018-03-23 12:39:29

标签: java android

如何向初始化对象添加新值?

Object[][] myData = new Object[][]{{1,2}, {3,4}};
int number1 = 5;
int number2 = 6;

在上面的代码中,我必须在number1中添加number2myData。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您需要创建另一个更大的数组,并将旧数组中的项目复制到新数组,然后将新项目添加到该数组中。

更好的选择是使用ArrayList。将项添加到ArrayList时,如果需要,容量将在幕后增长;你不必担心增加尺寸。

  

使用您的代码

fastcgi_pass unix:/run/php/php7.2-fpm.sock;
  

使用ArrayList

Object[][] myData = new Object[][]{{1,2}, {3,4}};
int number1 = 5;
int number2 = 6;
Object[][] bigNewArray =  Arrays.copyOf(myData, myData.length +1 );
/*
  The +1 is to increase the size of the new created array, 
  you can increae it to how many numbers you want and datas accordingly. 
*/
bigNewArray[2] = new Object[]{number1, number2};
System.out.println(bigNewArray[2][0]); //Print out 5