Reputation: 1647
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.
Upvotes: 0
Views: 7950
Reputation: 1727
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) {
Upvotes: 3
Reputation: 7202
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.
Upvotes: 4