Java 将元素添加到第一个空数组的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25918532/
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
Adding an element to the first empty array's index
提问by Jared
I've created an array of size x . And want to add an element to the first empty index in the array .For example , if the array's size is 10 and indexes 1 and 2 are taken, then the element is added to index 3.
我创建了一个大小为 x 的数组。并且想在数组中的第一个空索引上添加一个元素。例如,如果数组的大小为10,并且取索引1和2,则将元素添加到索引3。
采纳答案by qbit
If the array is an int
array you can do
如果数组是一个int
数组,你可以做
for(int i=0; i < array.length; i++)
if(array[i] == 0) {
array[i] = newValue;
break;
}
if it is an Object
array you can do
如果它是一个Object
数组,你可以做
for(int i = 0; i < array.length; i++)
if(array[i] == null) {
array[i] = newObject;
break;
}
回答by Cratylus
Create the array of size x.
Create a stack of size x which indicates all free indexes. Push all indexes (in reverse order) to the stack.
When you try to add an element to the array pop from the stack the next free index. Use the index to insert to the array.
If an element is removed, push the index back to the stack to indicate that it is free and nullify the element in the array.
If you want to add an element and the stack is empty i.e. the array is full, well you decide what to do.
创建大小为 x 的数组。
创建一个大小为 x 的堆栈,表示所有空闲索引。将所有索引(以相反的顺序)推入堆栈。
当您尝试向数组中添加元素时,会从堆栈中弹出下一个空闲索引。使用索引插入到数组中。
如果删除了一个元素,则将索引推回堆栈以指示它是空闲的,并使数组中的元素无效。
如果你想添加一个元素并且堆栈是空的,即数组已满,那么你决定做什么。
Your other option would be to loop over the array to find the next "free" spot which would be indicated by a null.
您的另一个选择是遍历数组以找到下一个由空值指示的“空闲”点。
回答by subham soni
Loop through the array until you find zero/null. For example,
循环遍历数组,直到找到零/空。例如,
int a[] = new int[100];
int x; //Number to be inserted
for(int i=0;i<a.length;i++)
{
if(a[i]==0)
a[i]=x;
}
object a[] = new object[100];
int x;
for(int i=0;i<a.length;i++)
{
if(a[i]==null)
a[i]= new Integer(x);
}
回答by John K
In the responses above, there is no early termination of the for-loop after the first empty index is found. To avoid all empty indexes being populated, add a break statement as part of the conditional statement.
在上面的响应中,在找到第一个空索引后没有提前终止 for 循环。为避免填充所有空索引,请添加 break 语句作为条件语句的一部分。
for(int i = 0; i < array.length; i++)
{
if(array[i] == null)
{
array[i] = newObject;
break;
}
}