怎么在数组中间放置一个元素

huangapple go评论65阅读模式
英文:

how do I place something in between an array

问题

我有一个数组:

char[] arr = {'h', 'e', 'l', 'o'};

我想在这个数组中间放入一些其他对象,就像这样:

char[] desired = {'h', 'e', 'l', 'l', 'o'};

所以,在这里我在 arr[2] = 'l' 处保留了一个 l,并在旧的 lo 之间添加了一个新的 l,但是在代码中我应该如何做到这一点?

英文:

I have an array:

char[] arr = {'h', 'e', 'l', 'o'};

and I want to put some other object in between that array, like:

char[] desired = {'h', 'e', 'l', 'l', 'o'};

So, here I kept l in arr[2] = 'l' and added new l in between old l and o, but how can I do this in the code?

答案1

得分: 2

数组具有固定的长度 - 在声明/赋值时指定。虽然有一些方法适用于您的用例,涉及创建一个新数组,并为存储附加字符的附加索引,但我建议您查看 ArrayList 类 - ArrayList 文档

简而言之,ArrayListList 接口的可调整大小的数组实现。需要注意的一点是,ArrayList 不允许存储原始值,因此在您的情况下,您必须使用非原始的 Character 包装器,而不是原始的 char 类型来存储值。ArrayList.add(index, element) 方法可用于在结构内的特定索引处插入特定元素 - 根据需要将其他元素沿数组移动以适应新元素。

以下是解决您原始问题的基本示例。

// 新的 Character 元素的 ArrayList,包含 ['h', 'e', 'l', 'o']
List<Character> al = new ArrayList<Character>(Arrays.asList('h', 'e', 'l', 'o'));
System.out.println("原始: " + al);	
al.add(2, 'l'); // 在索引 2 处插入元素 'l'
System.out.println("修改后: " + al);

输出:

原始: [h, e, l, o]
修改后: [h, e, l, l, o]
英文:

Arrays have a fixed length - that which is specified at declaration/assignment. Whilst there are methods that will work for your use case that involve creating a new array with additional indices for storing additional characters, I would recommend checking out the ArrayList class - ArrayList docs.

In short, an ArrayList is a resizeable array implementation of the List interface. One thing to note is that an ArrayList does not allow for the storage of primitive values, therefore in your case you would have to use the non-primitive Character wrapper instead of the primitive char type to store values. The ArrayList.add(index, element) method can be used to insert a specific element at a specific index within the structure - shifting other elements along the array as required to accommodate the new element.

Basic example illustrating a solution to your original question below.

// New ArrayList of Character elements contatining ['h', 'e', 'l', 'o']
List<Character> al = new ArrayList<Character>(Arrays.asList('h', 'e', 'l', 'o'));
System.out.println("Original: " + al);	
al.add(2, 'l'); // At index 2, insert element 'l' 
System.out.println("Modified: " + al);

Output:

Original: [h, e, l, o]
Modified: [h, e, l, l, o]

huangapple
  • 本文由 发表于 2020年9月3日 17:18:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63720534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定