gpt4 book ai didi

java - 如何在列表中的另一个项目之后添加一个项目?

转载 作者:搜寻专家 更新时间:2023-11-01 02:44:51 25 4
gpt4 key购买 nike

我想在列表中的特定项目之后添加一个项目。

例子:

"Item 1"
"Item 2"
"Item 3"
"Item 4"

添加新项目:

String newItem = "Item 5"
list.add(newItem);

现在我希望我添加的项目低于某个项目,让我们假设后者:

"Item 1"
"Item 2"
"Item 5"
"Item 3"
"Item 4"

最佳答案

List接口(interface)有方法void add(int index, E element)方法

Inserts the specified element at the specified position in this list (optional operation).

你的情况

list.add(2,newItem);

注意:索引从零开始。

在使用那个方法之前。只需检查以下异常(exception)情况

UnsupportedOperationException - if the add operation is not supported by this list
ClassCastException - if the class of the specified element prevents it from being added to this list
NullPointerException - if the specified element is null and this list does not permit null elements
IllegalArgumentException - if some property of the specified element prevents it from being added to this list
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

关于java - 如何在列表中的另一个项目之后添加一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25038889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com