您可以使用 ArrayList.add(int index, E element) 方法来实现这样的预期结果:
import org.junit.Test;
import java.util.ArrayList;
public class ArrayListInsertTest {
@Test
public void testWithArrayList() throws Exception {
ArrayList<String> list = new ArrayList<String>();
list.add("John");
list.add("is");
list.add("good");
list.add("boy");
list.add(3, "mike");
list.add(4, "Tyson");
System.out.println(list);
}
}
ArrayList 文档中的注释:
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {