[英]How can i place an element in an array on a given position?
I have the following question. 我有以下问题。
int[] ar={4,6,7,8}
Now i want to add an element so i get 现在我想添加一个元素,这样我就可以
ar={4,6,9,7,8}
I want to be able to add a given element (9) in a position that i want i this case index 2. How? 我希望能够在此案例索引2的位置添加给定元素(9)。如何?
In Java, the size of an array cannot be changed. 在Java中,无法更改数组的大小。 Instead you can use a
List
: 相反,您可以使用
List
:
List<Integer> numList = new ArrayList<Integer>();
numList.add(4);
numList.add(6);
numList.add(7);
numList.add(8);
Then you can use numList.add(int index, E element);
然后可以使用
numList.add(int index, E element);
to insert values at specific positions. 在特定位置插入值。
numList.add(2, 9);
//numList = {4, 6, 9, 7, 8};
For further information you may want to look at this tutorial . 有关更多信息,您可能需要阅读本教程 。
Java arrays are fixed length, so you'll need to create another one to store your extra element. Java数组是固定长度的,因此您需要创建另一个数组来存储您的额外元素。
int[] ar = { 4, 6, 7, 8 };
int[] tmp = new int[ar.length + 1];
int pos = 2;
for (int i = 0; i < pos; i++) {
tmp[i] = ar[i];
}
for (int i = pos + 1; i <= ar.length; i++) {
tmp[i] = ar[i - 1];
}
tmp[pos] = 9;
System.out.println(Arrays.toString(tmp));
Output is (as requested) 输出是(根据要求)
[4, 6, 9, 7, 8]
How to add new elements to an array? 如何将新元素添加到数组?
add an element to int [] array in java 在Java中将元素添加到int []数组中
Note that ArrayList also has an add method that lets you specify an index and the element to be added void add(int index, E element)
. 请注意,ArrayList也有一个add方法,该方法可让您指定索引和要添加的元素
void add(int index, E element)
。
The most simple way of doing this is to use an ArrayList<Integer>
and use the add(int, T)
method. 最简单的方法是使用
ArrayList<Integer>
并使用add(int, T)
方法。
List<Integer> numList = new ArrayList<Integer>();
numList.add(4);
numList.add(6);
// Now, we will insert the number
numList.add(2, 9);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.