I dont know what is the best way to check if my object in my list is the last created.
What would be the optimal method to do it ?
Should I get the last element in the list and check if my given element is the last ?
I dont know what is the best way to check if my object in my list is the last created.
What would be the optimal method to do it ?
Should I get the last element in the list and check if my given element is the last ?
use this check
listObj.indexOf(yourObject) == (listObj.size() -1);
Note:The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
If you're looking to order your objects by a specific property (such as it's date property), take a look at the Comparable interface (http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html). If you implement this interface (or a Comparator), the collections provided by the Java API can be used to automatically sort the objects.
This depends a lot on your implementation.
If your objects are appended to the end of the list in order of creation then the first item in the list (index 0) will be the oldest.
If the objects in your list are appended in an unknown order and your objects have a method to query the creation date, you could either:
Option 1 incurs overhead when items are added to the list or when you explicitly sort the list. Option 2 has overhead when you want to retrieve the oldest object.