gpt4 book ai didi

Java数组改变大小

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:41:44 26 4
gpt4 key购买 nike

我需要更改一个数组的大小,但我不能简单地创建另一个数组 - 它需要相同的名称以便我可以将它传递给一个方法。具体来说,我需要数组的项数是以前的两倍。这可能与一个数组有关吗?我可以将数据从数组 A 复制到数组 B,然后使用 A = B 使 A 引用与 B 相同的数据吗? ?

最佳答案

我使用了 Arrays.copyOf 方法,如下所示:

    int myArray[] = {1,2,3};
myArray = Arrays.copyOf(myArray, myArray.length+1);
//previous line creates a copy of the array and adds one to the size

myArray[3] = 12; // assign the new fourth element the value of 12
//then loop through the array to output each element
for(int ctr = 0; ctr<myArray.length; ctr++){
System.out.println(myArray[ctr]);
}

关于Java数组改变大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8869419/

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