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 ?
-
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.recursion.ninja– recursion.ninja2013年04月14日 18:15:05 +00:00Commented Apr 14, 2013 at 18:15
3 Answers 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.
Comments
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.
Comments
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");