7

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 ?

Community
  • 1
  • 1
Adil
  • 4,503
  • 10
  • 46
  • 63
  • 2
    If you use `add(element)` yes as it "Appends the specified element to the end of this list.", if you use `add(index, element)` it can be anywhere. – Peter Lawrey Sep 19 '12 at 10:16

3 Answers3

14

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

israelC
  • 457
  • 4
  • 6
4

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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 1
    Unless you tell it otherwise with `add(index, element)` – Peter Lawrey Sep 19 '12 at 10:17
  • 1
    No insertion time needed, that would be overkill; just keep record of the last element added. But this works only if you have the class under your control; judging from OP's question it seems like he's dealing with a pre-existing `ArrayList`. – Marko Topolnik Sep 19 '12 at 10:20
  • @Marko yes that would be better – jmj Sep 19 '12 at 10:21
  • ...except if you also want to support the case where elements are *removed* and you still want the last element added! Then something like your solution would be the only option, but still not keeping time, but sequence of addition operation. Otherwise it would be almost typical to see the same addition time for many elements added is rapid succession. – Marko Topolnik Sep 19 '12 at 10:24
1

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.

mishadoff
  • 10,719
  • 2
  • 33
  • 55