Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last added element Arraylist

Tags:

java

arraylist

How can we get the last added element in ArrayList. I find this that explain how to get the last element, but is the last added element always the last element ?

like image 207
Adil Avatar asked Sep 19 '12 10:09

Adil


2 Answers

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:

yourArrayList.get(yourArrayList.size()-1);

Your answer is in the link that you said :)

like image 86
israelC Avatar answered Sep 18 '22 15:09

israelC


Yes for ArrayList, It preserves the order of insertion

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

or better have a reference pointing to last inserted item as Marko Topolnik suggested, also maintain it on removal

Better thing would be use LinkedHashSet, if you are not concerned about uniqueness property of set

like image 38
jmj Avatar answered Sep 19 '22 15:09

jmj