问题
Below is the method add()
of Java List
Interface
; if I loop through it 7 times adding i
to the 0
th 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:
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.
回答2:
according to this doc on list List for Java it pushes the element to the right of the list adding one to the indices
回答3:
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.
来源:https://stackoverflow.com/questions/26311369/java-list-add-method