0
import java.util.ArrayList;
public class ArrayTest {
 private static ArrayList<String> list = new ArrayList<String>();
 public static void printList () {
 System.out.println("Printing the list");
 for (int i = 0; i < list.size(); i++)
 {
 if (list.get(i) != null)
 System.out.println(i + " => " + list.get(i));
 } 
 }
 public static void add(Integer index, String val) {
 while(list.size() <= index)
 list.add(null);
 list.add(index, val); 
 } 
 public static void main(String[] args) {
 ArrayTest.add(8, "cover");
 ArrayTest.printList();
 ArrayTest.add(6, "and");
 ArrayTest.printList();
 } 
}

produces the following output

Printing the list
8 => cover
Printing the list
6 => and
9 => cover

The add(Integer index, String val) function adds an appropriate number of nulls to the list as a check to avoid any IndexOutOfBoundsException exceptions. Can someone explain why does adding "and" to the list push "cover" a position further in the list ?

asked Apr 14, 2013 at 18:09
1
  • Read the documentation, the ArrayList.add(int,element) inserts an element at the specific index, shifting subsequent elements back. The ArrayList.set(int, element) sets the element at the index without shifting. Commented Apr 14, 2013 at 18:15

3 Answers 3

3

Because the add method you used inserts an element at specified index. It doesn't replace the existing element at this position, it add a new, so add the index position from that towards the end.

If you need to replace the value, use the set method.

answered Apr 14, 2013 at 18:15

Comments

2

Because this is the actual specification of the List.add(int index, E element) method:

Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

As to "why": this is done to avoid overwriting the element on the specified position.

answered Apr 14, 2013 at 18:16

Comments

0

In Java 9, there's an easy way with less number of lines without needing to initialize or add method. Use collection factory methods:

List<String> list = List.of("first", "second", "third");
answered Apr 10, 2018 at 9:06

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.