1

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 ?

2
  • 3
    JavaDocs are your friend. Check out List.add(int, E). Commented Oct 17, 2014 at 13:58
  • ArrayList class will take care of rearranging the elements after an insert (in whichever position you want). You'd have to do it yourself if you were using static arrays. Commented Oct 17, 2014 at 14:01

2 Answers 2

6

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]
Sign up to request clarification or add additional context in comments.

4 Comments

Oh ok ! So if i use the method and tell it to add at the 0 position it will bump all the other element of 1 space in the liste ? I tought it wouldve replace the element
Correct, it will shift the other elements. No, that's List#set(int,E).
So List# set (int, E) will replace the element at the given position ? Ok ... sounds good. I tought i had to copy everything in the list and move in another to insert everything again.
@Cyberflow The docs for List.add(int, E) explicitly mention the bumping: "Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices)."
0

Functionally:

Integer toPrepend = 7;
List<Integer> initial = List.of(1,  3,  5,  6);

Stream.concat(Stream.of(toPrepend), initial.stream()).collect(Collectors.toList())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.