爪哇 - 添加元素到数组 [英] Java - Add Element to an Array
问题描述
看了看四周,找不到在Java中的任何类似的问题。
基本上我需要一些在特定位置索引添加到一个int数组
我只能用数组,没有的ArrayList
下面是我到目前为止,我知道为什么它不工作,但我无法弄清楚如何解决覆盖,我不希望它做的这个问题。
的任务是一个非覆盖刀片。例如最终的结果将是
[1 2 3 1337 4 5 6 7 8]
下面是code片断:
公共无效的主要(字串[] args)
{
INT []数组= {1,2,3,4,5};
阵列=添加(数组,2,1337);
对于(INT I:数组)
System.out.print第(i +);
}
公众诠释[]加(INT [] myArray的,诠释POS,INT N)
{
的for(int i = POS; I< myArray.length-1;我++){
myArray的[I] = myArray的第[i + 1];
}
myArray的[POS] = N;
返回myArray的;
}
您的问题是这样的循环:
的for(int i = POS; I< myArray.length-1;我++){
myArray的[I] = myArray的第[i + 1];
}
据写入 I + 1
到 I
- 即它的动作元素的下的 - 你需要它来移动它们的最多的。为了拉升,需要迭代的下的(否则你覆盖你刚才写的)。结果
试试这个:
的for(int i = myArray.length - 1; I> POS;我 - ){
myArray的[I] = myArray的[我 - 1];
}
请注意,这将通过丢失(覆盖)的最后一个元素使房间的插入在 POS
。
Looked around, couldn't find any similar questions in java..
Basically I need to add a number to an int array in a specific position index
I can only use Arrays, no ArrayLists
Here is what I have so far, and I know why it doesn't work, but I can't figure out how to fix that problem of overwriting, which I don't want it to do.
The task is a non-overwriting insert. e.g. the final result would be
[1 2 1337 3 4 5 6 7 8]
Here is the code snippet:
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;
}
Your problem is this loop:
for (int i = pos; i<myArray.length-1; i++){
myArray[i] = myArray[i+1];
}
It is writing i+1
into i
- ie it moves element down - you need it to move them up. In order to move up, you need to iterate down (otherwise you overwrite what you just wrote).
Try this:
for (int i = myArray.length - 1; i > pos; i--) {
myArray[i] = myArray[i - 1];
}
Note that this will make room for the insertion at pos
by losing (overwriting) the last element.
这篇关于爪哇 - 添加元素到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!