gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:03:32 27 4
gpt4 key购买 nike

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

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

在上面的代码中,我必须在 myData 中添加 number1number2。我该怎么做?

最佳答案

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

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

Using your code

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

Using ArrayList

ArrayList<Object[]> myData1 = new ArrayList<Object[]>();
Object[] one = new Object[]{1,2};
Object[] two = new Object[]{3,4};
Object[] three = new Object[]{5,6};

myData1.add(one);
myData1.add(two);
myData1.add(three);
//you can add as many object to it as you want
System.out.println(myData1.get(2)[0]); //Print out 5

关于java - 如何在 Java 中向已初始化的对象 [][] 添加新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49449884/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com