java arraylist prepend code example

Example 1: java append to arraylist at beginning

ArrayList<Integer> arr = new ArrayList<Integer>();

arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);

int element = 0;

//ArrayList.add(index, element)
arr.add(0, element);

Example 2: java arraylist add to top

//create an ArrayList
  ArrayList<String> myList 
                = new ArrayList<String>();
        
//some items to ArrayList
myList.add("One");
myList.add("Two");
myList.add("Three");

/*
* To insert element at beginning of ArrayList
* use add method of ArrayList class with index 0
*/

myList.add(0, "Zero");

Tags:

Java Example