如何向ArrayList的第一个元素追加数据?

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

How to append into first element of Arraylist?

问题

例如:我的ArrayList是:[S1 10 20 12, S2 11 21 13, S3 13 10 12]
因此,我想在第一个位置添加额外的元素**(99),保持之前的元素不变[S1 10 20 12]**
我的输出应该是[S1 10 20 12 99, S2 11 21 13, S3 13 10 12]

英文:

For eg:- my Arraylist is :-
[S1 10 20 12, S2 11 21 13, S3 13 10 12]
Thus i want to add extra element (99) in first place keeping previous ones as they were [S1 10 20 12]
My output should be [S1 10 20 12 99, S2 11 21 13, S3 13 10 12]

答案1

得分: 2

Use the get method to read the first element from the list, and the set method to write the modified value. Read the API documentation to see what methods are available for lists: https://docs.oracle.com/javase/10/docs/api/java/util/List.html

String firstItem = list.get(0);
list.set(0, firstItem + " 99");
英文:

Use the get method to read the first element from the list, and the set method to write the modified value. Read the API documentation to see what methods are available for lists: https://docs.oracle.com/javase/10/docs/api/java/util/List.html

String firstItem = list.get(0);
list.set(0, firstItem + " 99");

</details>



# 答案2
**得分**: 1

Use add with index as first parameter: 使用带有索引作为第一个参数的add方法:public void add(int index, E element)

<details>
<summary>英文:</summary>

Use add with index as first parameter: public void add(int index, E element)

</details>



# 答案3
**得分**: 0

你可以考虑使用链表(LinkedList),如果这个列表非常大,插入操作会更加便宜。

<details>
<summary>英文:</summary>

You might want to consider a LinkedList where insertion is cheaper if this list is very big.

</details>



# 答案4
**得分**: 0

你可以使用```LinkedList.addFirst()```,它具有最佳性能。但你必须记住,你需要将你的列表声明为```LinkedList```实例,而不是更通用的接口```List```。

第二种方法是使用两个参数的```List.add(int index, E Element)```方法。然后你可以将你的列表声明为```List```。

<details>
<summary>英文:</summary>

You can use ```LinkedList.addFirst()``` which has the best performance. But you have to remember, that you are obligated to declare instance your list as ```LinkedList```, instead of a more universal interface ```List```.

The second way is to use two arguments ```List.add(int index, E Element)``` method. Then you can have your list declared as ```List```.

</details>



huangapple
  • 本文由 发表于 2020年8月7日 12:09:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63295053.html
匿名

发表评论

匿名网友

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

确定