Java 如何将值添加到数组的指定索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19041380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a value to a specified index of array
提问by JhonF
I tried to add an integer to the 4th index of the array. But it is adding after remove the 4th element.
我试图在数组的第 4 个索引中添加一个整数。但它是在删除第 4 个元素后添加的。
int ar[] = {1,2,3,4,5,7,8,9};
int position = 4;
for(int i=0;i<ar.length;i++){
if(i==position){
ar[i] = 6;
}
System.out.println(ar[i]);
}
采纳答案by Vulcronos
You are replacing the fifth item with the number six. A faster way to do it would be:
您正在用数字 6 替换第五项。更快的方法是:
ar[position] = 6;
Since you are using Java, I would try to use an arraylist. They have methods that let you add items at a given index. If you can't do that, you will need to shift everything over.
由于您使用的是 Java,我会尝试使用数组列表。他们有一些方法可以让你在给定的索引处添加项目。如果你不能做到这一点,你就需要把一切都转移过来。
int previous = 6;
int current = 0;
for(int i=position;i<ar.length;i++){
current = ar[i];
ar[i] = previous;
previous = current;
}
If your array is full you will lose the last number though.
如果您的数组已满,您将丢失最后一个数字。
回答by newuser
int position = 3; Array starts from 0. 4th index points the fifth value.
int position = 3;
if(ar.length > position)
{
ar[position] = 6;
}
回答by TheKojuEffect
Array indexing start from 0
, So to insert in 4th place you have to do array[3] = value
. So, you'll have to put position = 3
数组索引从 开始0
,因此要插入到第 4 位,您必须这样做array[3] = value
。所以,你必须把position = 3
int position = 3; // array index start from 0
Also, since you're using an array, while adding, you'll replace it. If you want to add without replacement, use ArrayList.
此外,由于您使用的是数组,因此在添加时将替换它。如果要添加而不替换,请使用ArrayList。
Refer to this ArrayList Examplesif you're unfamiliar with it.
如果您不熟悉它,请参阅此ArrayList 示例。
回答by Sotirios Delimanolis
With the following line of code
使用以下代码行
ar[i] = 6;
you are assigning the value 6
to the element at index i
. You aren't adding a new element and expecting the array to shift all other positions. An array is of fixed size.If you want a data structure that can grow, use an ArrayList
.
您正在将值分配给6
index 处的元素i
。您不会添加新元素并期望数组移动所有其他位置。数组是固定大小的。如果您想要一个可以增长的数据结构,请使用ArrayList
.
ArrayList<Integer> ar = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 7, 8, 9));
int position = 4;
ar.add(i, 6);
System.out.println(ar);
The add(int, T)
method shifts all elements at the current i
index to the right and inserts the specified element at i
. The above will print
该add(int, T)
方法将当前i
索引处的所有元素向右移动,并在 处插入指定的元素i
。以上将打印
[1, 2, 3, 4, 6, 5, 7, 8, 9]
You would need to insert at index 5
.
您需要在 index 处插入5
。