java 获取最后添加的元素 Arraylist
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12492692/
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
Get last added element Arraylist
提问by Adil
采纳答案by Jigar Joshi
Yes for ArrayList
, It preserves the order of insertion
Yes for ArrayList
,它保留插入顺序
If you explicitly add the element at particular position by specifying index add()
, in this case you need to set insertion time by customizing ArrayList implementation and while retrieving the latest inserted element consider that time in calculation
如果您通过指定 index 在特定位置显式添加元素add()
,在这种情况下,您需要通过自定义 ArrayList 实现来设置插入时间,并在检索最新插入的元素时在计算中考虑该时间
or better have a reference pointing to last inserted item as Marko Topolniksuggested, also maintain it on removal
或者最好有一个参考指向最后插入的项目,如 Marko Topolnik建议的那样,在删除时也保持它
Better thing would be use LinkedHashSet
, if you are not concerned about uniqueness property of set
LinkedHashSet
如果您不关心 set 的唯一性属性,则最好使用
回答by israelC
Yes, as the other people said, ArrayList
preserves insert order. If you want the last added element, (only if you always add your elements with add(element)
) just type this:
是的,正如其他人所说,ArrayList
保留插入顺序。如果您想要最后添加的元素,(仅当您总是添加元素时add(element)
)只需输入:
yourArrayList.get(yourArrayList.size()-1);
Your answer is in the link that you said :)
你的答案在你说的链接中:)
回答by mishadoff
If you are using add(element)
signature, your last element in ArrayList
always be last inserted element.
如果您使用add(element)
签名,则您的最后一个元素ArrayList
始终是最后插入的元素。
If you are using add(index, element)
you can't know exactly which is last one. Simplest solution to create your subclass of ArrayList
that will hold last inserted element in special variable.
如果您正在使用,add(index, element)
您将无法确切知道哪一个是最后一个。创建子类的最简单解决方案ArrayList
将在特殊变量中保存最后插入的元素。