0

I have below scenario:

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

expected output: ("john","is","good","mike","Tyson","boy")

But i am getting array out of bond exception.

Can some one please suggest.

3
  • Got it :) Thanks Guglielmo Moretti Commented Sep 27, 2013 at 7:35
  • Have you tried debugging it? At which line does the exception occur? I also think that you're using "set" wrong. "Set" will replace an item, not add it somewhere in between. Commented Sep 27, 2013 at 7:35
  • I did not get any exception. Commented Sep 27, 2013 at 7:36

2 Answers 2

4

Use java.util.List#set(int index, E element) to replace the element at any position

Use java.util.List#add(int index, E element) to add the element to any position.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use ArrayList.add(int index, E element) method to achieve desired result like this:

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);
    }
}

Note from documentation of 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) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.