Reputation: 1407
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 ?
Upvotes: 0
Views: 5460
Reputation: 3439
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");
Upvotes: 0
Reputation: 13181
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.
Upvotes: 2
Reputation: 13792
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.
Upvotes: 3