假设我有一个大小为 n 的对象 ArrayList。现在我想在特定位置插入另一个对象,比如索引位置 k(大于 0 且小于 n),并且我希望索引位置 k 及其之后的其他对象向前移动一个索引位置。那么是否有直接在 Java 中完成此操作的方法?实际上,我想在添加新对象时保持列表排序。
要在特定索引处向ArrayList中 插入 值,使用以下方法:
public void add(int index, E element)
这个方法将会移动列表中后续的元素,但你无法保证插入的新对象会按照排序顺序放置在正确的位置上,因此可能导致列表不再有序。
要替换指定位置的元素,请使用:
public E set(int index, E element)
这个方法用指定的元素替换列表中指定位置的元素,并返回先前在该位置的元素。
这是一个简单的数组列表示例,用于在特定索引处插入元素。
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]
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)
来自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.
arrayList.add(1,"INSERTED ELEMENT");
,其中1是位置。当向特定位置添加内容时,您必须自己处理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)
}
}
add()
是可选的,这意味着并非所有 Java 实现的ArrayList
或一般的List
对象都必定支持此方法。 - EntangledLoops