将元素添加到数组java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9823503/
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
Add element into array java
提问by user1284791
Here's what the layout is
这是布局
index num
0 [10]
1 [20]
2 [30]
(Add 35 here)
3 [40] Move elements down
4 [50]
5 [60]
6 [70]
then my method is this
那么我的方法是这样的
public static void method(int[] num, int index, int addnum)
{
}
How can i add 35 in there?
我怎样才能在那里添加 35?
Tried this:
试过这个:
public static void method(int[] num, int index, int addnum)
{
int index = 10;
for(int k = num.length k>3; k++)
{
Num[k]=num[k++]
}
Num[3] = 35;
回答by aioobe
You need to
你需要
allocate a new array with room for one new element.
int[] newArray = new int[oldArray.length + 1];
Copy over all elements and leave room for the one to insert.
for (int i = 0; i < newArray.length - 1; i++) newArray[i < insertIndex ? i : i + 1] = oldArray[i];
Insert 35 in the empty spot.
newArray[insertIndex] = numberToInsert;
为一个新元素分配一个有空间的新数组。
int[] newArray = new int[oldArray.length + 1];
复制所有元素并为要插入的元素留出空间。
for (int i = 0; i < newArray.length - 1; i++) newArray[i < insertIndex ? i : i + 1] = oldArray[i];
在空白处插入 35。
newArray[insertIndex] = numberToInsert;
Note that it's notpossible to do in a method like this:
需要注意的是它不能够在这样的方法来做:
public static void method(int[] num, int index, int addnum)
^^^^
since you can'tchange the length of num
.
因为你不能改变num
.
You needto allocate a new array, which means that need to returnthe new array:
您需要分配一个新数组,这意味着需要返回新数组:
public static int[] method(int[] num, int index, int addnum)
^^^^^
and then call the method like this:
然后像这样调用方法:
myArr = method(myArr, 3, 35);
回答by amit
Well, you can't unless there is "extra space" in your array, and then you can shift all elements [starting from index
] one element to the right, and add 35 [num
] to the relevant place.
[what actually happen is that the last element is discarded out].
好吧,除非您的数组中有“额外空间”,否则您不能这样做,然后您可以将所有元素 [从index
] 向右移动一个元素,并将 35 [ num
]添加到相关位置。
[实际发生的是最后一个元素被丢弃]。
However - a better solution will probably be to use an ArrayList, and use the method myArrayList.add(index,element)
但是 - 更好的解决方案可能是使用ArrayList,并使用该方法myArrayList.add(index,element)
回答by Woot4Moo
Since this very closely resembles homework what you need to realize is that you cannot dynamically increase the size of an array. So in your function:
由于这非常类似于家庭作业,因此您需要意识到您无法动态增加数组的大小。所以在你的函数中:
public static void(int[] num, int index, int addnum)
{
int[] temp = new int[num.length *2];
for(int i = 0; i < index; i++)
copy num[i] into temp[i]
insert addnum into temp[index]
fill temp with remaining num values
}
That pseudocode above should get you started.
上面的伪代码应该可以帮助您入门。
回答by jefflunt
What you're looking for is an insertion sort.
您正在寻找的是插入排序。
It's classwork, so it's up to you to figure out the proper code.
这是课堂作业,因此由您来找出正确的代码。
回答by DukeOfMarmalade
Very crudely, you want to do something like this:
非常粗略地,你想做这样的事情:
public static void(int[] num, int index, int addnum)
{
// initialize new array with size of current array plus room for new element
int[] newArray = new int[num.length + 1];
// loop until we reach point of insertion of new element
// copy the value from the same position in old array over to
// same position in new array
for(int i = 0; i < index; i++)
{
newArray[i] = num[i];
}
i = i + 1; // move to position to insert new value
newArray[i] = addnum; // insert the value
// loop until you reach the length of the old array
while(i < num.length)
{
newArray[i] = num[i-1];
}
// finally copy last value over
newArray[i + 1] = num[i];
}
回答by soulmerge
As this is something you should accomplish yourself, I will only provide the method to implement it, not the code:
由于这是你应该自己完成的事情,我只会提供实现它的方法,而不是代码:
If you would set the number at position index
, you would overwrite the value that was there previously. So what you need to do is move every element one position towards the end of the array starting from index
: num[x]
becomes num[x+1]
, etc.
如果您在 position 处设置数字index
,您将覆盖之前存在的值。所以,你需要做的是一个位置移动的每一个元素朝从开始数组的末尾index
:num[x]
变num[x+1]
等。
You will find out that you need to do this in reverse order, otherwise you will fill your array with the value in num[index]
.
您会发现您需要以相反的顺序执行此操作,否则您将使用中的值填充数组num[index]
。
During this process you will need to decide what to do with the last entry of the array (num[num.length - 1]
):
在此过程中,您需要决定如何处理数组 ( num[num.length - 1]
)的最后一个条目:
- You could just overwrite it, discarding the value
- You could return it from your function
- You could throw an exception if it is non-zero
- You could create a new array that is 1 entry larger than the current array instead to keep all values
- etc.
- 您可以覆盖它,丢弃该值
- 你可以从你的函数中返回它
- 如果非零,您可以抛出异常
- 您可以创建一个比当前数组大 1 个条目的新数组,以保留所有值
- 等等。
After this, you have duplicated num[index]
: the value is present in num[index+1]
, too, as you have moved it away.
在此之后,您复制了num[index]
:该值也存在于 中num[index+1]
,因为您已将其移开。
Now it is possible to write the new value at the desired position without overriding an existing value.
现在可以在所需位置写入新值而不覆盖现有值。
EDIT
编辑
You have several errors in your code:
您的代码中有几个错误:
- You increment
k
, you need to decrementit (k--
, notk++
) - You modify
k
again in your loop body: it is updated twice in each cycle - If you start with
k = num.length
, you will try to write atnum[num.length + 1]
, which is not possible
- 你增加
k
,你需要减少它(k--
,不是k++
) - 您
k
在循环体中再次修改:它在每个循环中更新两次 - 如果您从 开始
k = num.length
,您将尝试写在num[num.length + 1]
,这是不可能的
回答by Arijit
How about this?
这个怎么样?
public class test {
public static void main(String[] arg) throws IOException
{
int[] myarray={1,2,3,5,6};//4 is missing we are going to add 4
int[] temp_myarray=myarray;//take a temp array
myarray=addElement(myarray,0);//increase length of myarray and add any value(I take 0) to the end
for(int i=0;i<myarray.length;i++)
{ if(i==3) //becaues I want to add the value 4 in 4th place
myarray[i]=4;
else if(i>3)
myarray[i]=temp_myarray[i-1];
else
myarray[i]=temp_myarray[i];
}
for(int i=0;i<myarray.length;i++)
System.out.print(myarray[i]);//Print new array
}
static int[] addElement(int[] arr, int elem) {
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = elem;
return arr;
}
}