Search code examples
javaarraylistinsert

Adding an element to the begining of an ArrayList in java


Just wondering what's the proper concept to add an element at the first position of a list ?

For example :

The primary list has these elements :

1 3 5 6

And id like to add this element at the beginning (position 0) : 7

So it would be like this at the final :

7 1 3 5 6

Do i need to copy all the elements in a temporary Arraylist and re-insert everything one at a time ?


Solution

  • You could use List.add(0, E) like

    List<Integer> al = new ArrayList<Integer>(Arrays.asList(1, 3, 5, 6));
    al.add(0, 7);
    System.out.println(al);
    

    Output is (as requested)

    [7, 1, 3, 5, 6]