arraylist how to add at 0 java code example

Example: arraylist how to add at 0 java

//The add(int index, E element) method of Java ArrayList class 
//inserts a specific element in a specific index of ArrayList. 
//It shifts the element of indicated 
//index if exist and subsequent elements to the right.
List<String> colors = new ArrayList<>();
colors.add("red");      // ["red"]  
colors.add("blue");     // ["red" , "blue"]  
colors.add(1, "white"); // ["red" , "white", "blue"]  
colors.add(0, "black"); // ["black", "red" , "white", "blue"]

Tags:

Java Example