【发布时间】:2011-10-27 19:30:58
【问题描述】:
假设我有一个大小为 n 的对象的 ArrayList。现在我想在特定位置插入另一个对象,假设在索引位置 k(大于 0 且小于 n),我希望索引位置 k 处和之后的其他对象向前移动一个索引位置。那么有没有办法直接在Java中做到这一点。实际上我想在添加新对象时保持列表排序。
【问题讨论】:
假设我有一个大小为 n 的对象的 ArrayList。现在我想在特定位置插入另一个对象,假设在索引位置 k(大于 0 且小于 n),我希望索引位置 k 处和之后的其他对象向前移动一个索引位置。那么有没有办法直接在Java中做到这一点。实际上我想在添加新对象时保持列表排序。
【问题讨论】:
来自 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.
【讨论】:
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)
}
}
【讨论】:
请注意,当您在某个位置插入列表时,您实际上是在列表当前元素内的动态位置插入。见这里:
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)
【讨论】:
这是在特定索引处插入的简单数组列表示例
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]
【讨论】:
实际上,针对您的特定问题的方法是arrayList.add(1,"INSERTED ELEMENT");,其中 1 是位置
【讨论】:
要将值插入到特定索引处的 ArrayList,请使用:
public void add(int index, E element)
此方法将移动列表的后续元素。但您不能保证列表将保持排序,因为您插入的新对象可能会根据排序顺序位于错误的位置。
要替换指定位置的元素,使用:
public E set(int index, E element)
此方法替换指定位置的元素 包含指定元素的列表,并返回之前的元素 在指定位置。
【讨论】:
add() 是可选的,这意味着并非所有ArrayList 或List 对象的Java 实现通常都必须支持此方法。