java ArrayList<string> 在最后一个位置添加项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36205092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ArrayList<string> add item in pre last position
提问by Peter
I try to create an ArrayList with fixed last item.
For example, in the ArrayList [0,1,2,last]
, I am trying to add an item in the second last position instead of last one. So, if i want to add a new item(say 3
) before last
and i do something like arraylist.add(3)
then it will give output [0,1,2,last,3]
which is clearly not my requirement. Can any tell me how to do it?
我尝试创建一个带有固定最后一项的 ArrayList。例如,在 ArrayList 中[0,1,2,last]
,我试图在倒数第二个位置而不是最后一个位置添加一个项目。所以,如果我想在之前添加一个新项目(比如3
)last
并且我做了类似的事情,arraylist.add(3)
那么它会给出[0,1,2,last,3]
显然不是我要求的输出。有谁能告诉我怎么做吗?
回答by Titus
You can use the add(int index, E element)method.
您可以使用add(int index, E element)方法。
Here is an example:
下面是一个例子:
list.add(list.size() - 1, 3);
回答by Aytunc Beken
You can also use this way, which handle if array's size is zero.
您也可以使用这种方式,如果数组的大小为零,则处理。
arraylist.add( (arraylist.size() == 0 ? 0:arraylist.size()-1), object);
回答by Nikolas
You can use add(int index, E element)
, that inserts the specified element at the specified position in this list.
您可以使用add(int index, E element)
, 在此列表中的指定位置插入指定元素。
arraylist.add(arraylist.size()-1, 3);
Insert your value to the end that is arraylist.size()
and minus 1 as the pre-last position.
将您的值插入到末尾,即arraylist.size()
减去 1 作为前最后一个位置。
回答by Yashasvi Raj Pant
You can add like this to address your problem:
您可以添加这样的内容来解决您的问题:
arraylist.add(arraylist.size()-1,3)
It will add the value in arraylist.size()-1
th position in the arrayList.
它将arraylist.size()-1
在 arrayList中的第 th 个位置添加值。