Java ArrayList替换特定索引

use*_*902 196 java arraylist

我需要帮助这个java.我创建了一个灯泡ArrayList,我试图用另一个灯泡替换特定索引的灯泡.因此,使用以下标题,我该如何处理?

public void replaceBulb(int index, Bulbs theBulb) {

}
Run Code Online (Sandbox Code Playgroud)

Mac*_*tle 342

查看List接口中set(int index, E element)方法

  • @AndroidKiller这是静态的`ArrayList.set();`但是当你在自己的列表中调用它时,它不是:`myArrayList.set(int,E);` (9认同)
  • 你是对的.但是你可能会想要编辑它,因为你的回答导致像set()方法这样的事实是不是静态方法,是吗? (3认同)

And*_*ler 117

您可以使用ArrayList的set方法替换特定位置的项目,如下所示:

list.set( your_index, your_item );
Run Code Online (Sandbox Code Playgroud)

但是元素应该出现在你在set()方法内传递的索引处,否则会抛出异常.

  • 成为新手意味着某人不知道如何正确编写代码。提供无效的代码总是错误的,没有任何借口,因为它可能并且通常会给初学者带来困惑。提供一个正确且自包含的代码示例就是StackOverflow的目的。感谢您对答案的改进。 (2认同)

Bur*_*ith 23

使用set()方法:参见doc

arraylist.set(index,newvalue);
Run Code Online (Sandbox Code Playgroud)


Kha*_*ela 7

public void setItem(List<Item> dataEntity, Item item) {
    int itemIndex = dataEntity.indexOf(item);
    if (itemIndex != -1) {
        dataEntity.set(itemIndex, item);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这仅在新项目与旧项目在 equals() 方法方面相等时才有效,对吗? (2认同)