[英]How to add an item to the top of the array and delete in Java?
我有:
[10, 20, 30, 40, 1000, 5000, 0, 5000]
我需要:
[-100,10, 20, 30, 40, 1000, 5000, 0]
如何在Java中将项目添加到顶部并删除数组中的项目?
应该这样做:
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
从数组中添加删除项非常昂贵。 您可以通过谷歌搜索找到很多示例。 但是我想在这里使用不同的数据结构。 在这种情况下,地图可能是一个很好的解决方案。 您可以这样使用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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.