如何元素添加到阵列和移位索引? [英] How to add an element to Array and shift indexes?
本文介绍了如何元素添加到阵列和移位索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个元素添加到数组指定位置和价值。
例如,我有阵
I need to add an element to Array specifying position and value. For example, I have Array
int []a = {1, 2, 3, 4, 5, 6};
应用addPos(INT 4,诠释87),它应该是在
after applying addPos(int 4, int 87) it should be
int []a = {1, 2, 3, 4, 87, 5};
据我所知,这里应该是数组的索引的转变,但看不到如何实现它在code。
I understand that here should be a shift of Array's indexes, but don't see how to implement it in code.
推荐答案
这应该做的伎俩:
public static int[] addPos(int[] a, int pos, int num) {
int[] result = new int[a.length];
for(int i = 0; i < pos; i++)
result[i] = a[i];
result[pos] = num;
for(int i = pos + 1; i < a.length; i++)
result[i] = a[i - 1];
return result;
}
其中, A
是原始数组, POS
是插入的位置,而民
要插入的数量。
Where a
is the original array, pos
is the position of insertion, and num
is the number to be inserted.
这篇关于如何元素添加到阵列和移位索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文