如何在特定位置向 ArrayList 中插入一个对象

88

假设我有一个大小为 n 的对象 ArrayList。现在我想在特定位置插入另一个对象,比如索引位置 k(大于 0 且小于 n),并且我希望索引位置 k 及其之后的其他对象向前移动一个索引位置。那么是否有直接在 Java 中完成此操作的方法?实际上,我想在添加新对象时保持列表排序。

6个回答

172

要在特定索引处向ArrayList中 插入 值,使用以下方法:

public void add(int index, E element)

这个方法将会移动列表中后续的元素,但你无法保证插入的新对象会按照排序顺序放置在正确的位置上,因此可能导致列表不再有序。


要替换指定位置的元素,请使用:

public E set(int index, E element)

这个方法用指定的元素替换列表中指定位置的元素,并返回先前在该位置的元素。


但我认为它会替换掉该索引位置处的对象。 - Harshveer Singh
9
@Harsh,实际上没有什么需要考虑的 - 文档已经很明确地说明了这个方法的作用。http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add(int, E) - denis.solonenko
1
@Harsh,你可以使用set(int index, Object Obj)来替换。 - lowLatency
1
排序有什么问题吗?“您插入的新对象可能会根据排序顺序放置在错误的位置”,因此,如果我从0开始遍历ArrayList直到找到正确的插入位置,然后将其插入并使列表的右侧向右移动一个位置...为什么顺序被破坏了?PS Java很棒,Ruby更棒。 - light24bulbs
请注意,add() 是可选的,这意味着并非所有 Java 实现的 ArrayList 或一般的 List 对象都必定支持此方法。 - EntangledLoops

79

这是一个简单的数组列表示例,用于在特定索引处插入元素。

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

8
我更倾向于这个答案,因为它展示了呼叫的结果。 - aroth

2
请注意,当您在列表中插入一个位置时,实际上是在列表当前元素的动态位置上进行插入。请参见此处:

http://tpcg.io/0KmArS

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {

      // create an empty array list with an initial capacity
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

      // use add() method to add elements in the list
      arrlist.add(15, 15);
      arrlist.add(22, 22);
      arrlist.add(30, 30);
      arrlist.add(40, 40);

      // adding element 25 at third position
      arrlist.add(2, 25);

      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }  
   }
}

$javac com/tutorialspoint/ArrayListDemo.java

$java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0
    at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661)
    at java.util.ArrayList.add(ArrayList.java:473)
    at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)

源代码已更改:https://www.tutorialspoint.com/java/util/arraylist_add_index.htm - Andrew

2

来自Oracle官方文档

此方法将指定的元素追加到列表末尾。

add(E e) //append element to the end of the arraylist.

该方法在列表的指定位置插入指定元素。

void add(int index, E element) //inserts element at the given position in the array list.

该方法用于将列表中指定位置的元素替换为指定的元素。

set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
      

      

从官方文档。 - Abdul Basit Rishi

0
实际上,在您的具体问题上执行此操作的方法是 arrayList.add(1,"INSERTED ELEMENT");,其中1是位置。

0

当向特定位置添加内容时,您必须自己处理ArrayIndexOutOfBounds。

为了方便起见,您可以在Kotlin中使用此扩展函数。

/**
 * Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
 */
fun <T> MutableList<T>.insert(index: Int, element: T) {
    if (index <= size) {
        add(index, element)
    } else {
        add(element)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接