我需要在Array中添加一个指定位置和值的元素.例如,我有阵列
int []a = {1, 2, 3, 4, 5, 6};
Run Code Online (Sandbox Code Playgroud)
应用后addPos(int 4, int 87)应该是
int []a = {1, 2, 3, 4, 87, 5};
Run Code Online (Sandbox Code Playgroud)
我知道这里应该是Array索引的转换,但是看不到如何在代码中实现它.
jra*_*rad 14
这应该做的伎俩:
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;
}
Run Code Online (Sandbox Code Playgroud)
a原始数组在哪里,pos是插入位置,num是要插入的数字.
最简单的方法是使用ArrayList<Integer>并使用该add(int, T)方法.
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
// Now, we will insert the number
list.add(4, 87);
Run Code Online (Sandbox Code Playgroud)
Jrad解决方案很好,但我不喜欢他不使用数组副本.在内部,System.arraycopy()执行本机调用,因此您可以获得更快的结果.
public static int[] addPos(int[] a, int index, int num) {
int[] result = new int[a.length];
System.arraycopy(a, 0, result, 0, index);
System.arraycopy(a, index, result, index + 1, a.length - index - 1);
result[index] = num;
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果您更喜欢使用 Apache Commons 而不是重新发明轮子,当前的方法是这样的:
a = ArrayUtils.insert(4, a, 87);
Run Code Online (Sandbox Code Playgroud)
它曾经是 ArrayUtils.add(...) 但不久前已被弃用。更多信息在这里:1
| 归档时间: |
|
| 查看次数: |
92552 次 |
| 最近记录: |