如何将项添加到数组的顶部并在Java中删除?

时间:2015-03-23 19:47:00

标签: java

我有:

[10, 20, 30, 40, 1000, 5000, 0, 5000]

我需要:

[-100,10, 20, 30, 40, 1000, 5000, 0]

如何在Java中添加项目并删除数组中的项目?

2 个答案:

答案 0 :(得分:0)

这应该这样做:

int[] array = [10, 20, 30, 40, 1000, 5000, 0, 5000];
int[] temp = array;

for (int i = 1; i < array.length; i++) {
    temp[i] = array[i - 1];
}

array = temp;
array[0] = -100; // the new input

答案 1 :(得分:0)

从数组中添加项目是非常昂贵的。你可以通过谷歌搜索找到很多例子。但我想在这里使用不同的数据结构。在这种情况下,Map可能是一个很好的解决方案您可以像这样使用Map -

Map<Integer, Integer> dummyArrayByMap = new HashMap<Integer, Integer>();   

之后,您可以使用dummyArrayByMap将任何元素放在任何索引上 -

dummyArrayByMap.put(3, 234) //put 234 at index 3
dummyArrayByMap.put(9, 234) //put 235 at index 9 
dummyArrayByMap.put(1, 234) //put 24 at index 1

当您尝试从第一个索引中删除某些内容时,您可以使用以下代码sniippet -

if(dummyArrayByMap.get(1)!=null){
   dummyArrayByMap.remove(1);
}

从第一个索引中删除元素后,您可以在第一个索引处再次添加新值 -

dummyArrayByMap.put(1, 387) // now new value is put at index 1 that means at first.