gpt4 book ai didi

Java - 将元素添加到数组

转载 作者:行者123 更新时间:2023-11-30 04:56:03 26 4
gpt4 key购买 nike

环顾四周,在java中找不到任何类似的问题..

基本上我需要将一个数字添加到 int 数组的特定位置索引

我只能使用数组,不能使用ArrayList

这是我到目前为止所拥有的,我知道为什么它不起作用,但我不知道如何解决覆盖问题,我不希望它这样做。

该任务是非覆盖插入。例如最终结果将是

[1 2 1337 3 4 5 6 7 8]

这是代码片段:

public void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8};
array = add(array, 2, 1337);
for(int i : array)
System.out.print(i + " ");
}


public int[] add(int[] myArray, int pos, int n)
{
for (int i = pos; i<myArray.length-1; i++){
myArray[i] = myArray[i+1];
}
myArray[pos] = n;
return myArray;
}

最佳答案

你的问题是这个循环:

for (int i = pos; i<myArray.length-1; i++){
myArray[i] = myArray[i+1];
}

它正在将 i+1 写入 i - 即它将元素向下移动 - 你需要它来将它们向上移动.为了向上移动,您需要向下迭代(否则您会覆盖刚刚编写的内容)。
试试这个:

for (int i = myArray.length - 1; i > pos; i--) {
myArray[i] = myArray[i - 1];
}

请注意,这将通过丢失(覆盖)最后一个元素来为 pos 处的插入腾出空间。

关于Java - 将元素添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8514046/

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