Best way to check if the item in the list is last (by date)

I do not know what is the best way to check if my object in my list is the last.

What would be the best method?

Should I get the last item in the list and check if this given item is the last?

+7
java collections list
source share
3 answers

use this check

listObj.indexOf(yourObject) == (listObj.size() -1); 

Note : List class <order - things will be saved to the list in the order in which you add them, including duplicates, unless you explicitly sort the list.

+18
source share

If you want to order your objects by a specific property (for example, the date property), see the Comparable interface ( http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html ). If you implement this interface (or Comparator), the collections provided by the Java API can be used to automatically sort objects.

+1
source share

It depends a lot on your implementation.

If your objects are added to the end of the list in the order they were created, the first item in the list (index 0) will be the oldest.

If the objects in your list are added in an unknown order, and your objects have a method for querying the creation date, you can either:

  • implement a sorted list based on the date the object was created
  • iterate over each item in your list and find the oldest object

Option 1 carries overhead when items are added to the list or when you explicitly sort the list. Option 2 has overhead if you want to get the oldest object.

+1
source share

All Articles