假设我有一个大小为 n 的对象的 ArrayList。现在我想在特定位置插入另一个对象,假设在索引位置 k (大于 0 且小于 n),并且我希望索引位置 k 处及其之后的其他对象向前移动一个索引位置。那么有没有什么方法可以直接在Java中做到这一点。实际上我想在添加新对象时保持列表排序。
要将 insert 值插入到 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是位置
为了方便起见,你可以在 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)
}
}
ArrayList<Integer> someData = new ArrayList<Integer>();
someData.add(1);
someData.add(2);
someData.add(3);
someData.add(4);
someData.add(5);
// currently someData = {1, 2, 3, 4, 5}
// Using add method with position someData = {1, 2, 3, 4, 6, 5}. size of array is increased
someData.add(5,6);
// Using set method with position someData = {1, 2, 3, 4, 7, 5}. Size remains same
someData.set(5,7);
阅读更多详细信息