如何将元素添加到 Array 并移动索引? [英] How to add an element to Array and shift indexes?

查看:31
本文介绍了如何将元素添加到 Array 并移动索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向 Array 添加一个元素,指定位置和值.例如,我有数组

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, int 87)后应该是

int []a = {1, 2, 3, 4, 87, 5};

我知道这里应该是 Array 的索引的移位,但不知道如何在代码中实现它.

I understand that here should be a shift of Array's indexes, but don't see how to implement it in code.

推荐答案

最简单的方法是使用 ArrayList 并使用 add(int, T) 方法.

The most simple way of doing this is to use an ArrayList<Integer> and use the add(int, T) method.

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);

这篇关于如何将元素添加到 Array 并移动索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆