Java List.add() method

不羁的心 提交于 2020-01-25 14:35:27

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!