0

我有以下情况:

ArrayList<String> list = new ArrayList<String>();

list.add("John");
list.add("is");
list.add("good");
list.add("boy");
int count = 2;
if (list.get(count-1)!= null)
{
    list.set(count+1, "mike");
    list.set(count+1,"Tysosn");
}

预期输出:("john","is","good","mike","Tyson","boy")

但是我正在摆脱债券异常。

有人可以建议。

4

2 回答 2

4

使用java.util.List#set(int index, E element)替换任意位置的元素

使用java.util.List#add(int index, E element)将元素添加到任何位置。

于 2013-09-27T07:36:44.453 回答
3

您可以使用 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) {
于 2013-09-27T07:38:24.960 回答