简体   繁体   中英

Get last added element 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 ?

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 :)

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

If you are using add(element) signature, your last element in ArrayList always be last inserted element.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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