0

Below is the method add() of Java List Interface; if I loop through it 7 times adding i to the 0th position like so.

for (int i = 0; i < 7; i++) {
    list.add(0, i);
}

Wouldn't it overwrite the value at that position, so I would end up with just one value of 6 in the list? Am I right, in assuming that?

1
  • Don't assume, try it out. Commented Sep 21, 2017 at 4:30

3 Answers 3

3

No, if you add at a position, it shifts everything starting at that position to the right.

So if you actually did this, you should end up with the following list:

[6, 5, 4, 3, 2, 1, 0]

Read the API: http://docs.oracle.com/javase/7/docs/api/java/util/List.html#add%28int,%20E%29

Or better yet, give it an actual try.

Sign up to request clarification or add additional context in comments.

Comments

1

according to this doc on list List for Java it pushes the element to the right of the list adding one to the indices

2 Comments

I actually figured that out, please see my comment above, but much appreciate your response Sir.
glad you got what you were looking for :)
1

Suppose we have,

mylist = ["Bashful","Awful","Jumpy","Happy"]

then,

mylist.add(2,"Doc") 

makes the ArrayList

mylist = ["Bashful","Awful","Doc","Jumpy","Happy"]

Notice that the indices of "Jumpy" and "Happy" have changed from 2 to 3, and 3 to 4, accordingly.

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.