动态添加元素到arraylist

时间:2013-09-27 07:30:51

标签: java arraylist

我有以下情况:

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")

但我正在摆脱债券例外。

有人可以建议。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

您可以使用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) {