views:

63

answers:

3

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 ?

+1  A: 

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.

org.life.java
listObj and list are the same in your example no ?
@user284237 oops typo ,yes updated the code
org.life.java
+1  A: 

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.

Dante617
A: 

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:

  1. implement a sorted list based on the object creation date
  2. iterate through every item in your list and find the oldest object

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.

Andy