简体   繁体   English

Java List.add()方法

[英]Java List.add() method

Below is the method add() of Java List Interface ; 下面是Java List Interface add()方法; if I loop through it 7 times adding i to the 0 th position like so. 如果通过它的7倍余环路加入i0像这样个位置。

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? 它不会覆盖该位置的值,所以我最终只会在列表中得到一个值为6的值吗? Am I right, in assuming that? 我猜对了吗?

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 阅读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. 还是更好,请尝试一下。

Suppose we have, 假设我们有

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

then, 然后,

mylist.add(2,"Doc") 

makes the ArrayList 使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. 请注意,“跳跃”和“快乐”的索引已相应地从2更改为3,并从3更改为4。

根据Java List List上的此文档,它将元素推到列表的右侧,从而向索引添加一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM