Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method to check if an object in a list is the last (by date)

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 ?

like image 541
Kévin_Bransard Avatar asked Oct 06 '10 16:10

Kévin_Bransard


People also ask

How do you check if an item is the last in a list Python?

There is 2 indexing in Python that points to the last element in the list. list[ len – 1 ] : This statement returns the last index if the list. list[-1] : Negative indexing starts from the end.

How do you check if that is the last element in list Java?

Approach: Get the ArrayList with elements. Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.

How do you find the last object of an ArrayList?

The size() method returns the number of elements in the ArrayList. The index values of the elements are 0 through (size()-1) , so you would use myArrayList. get(myArrayList. size()-1) to retrieve the last element.

How do you check if an object is in a list Java?

contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present.


2 Answers

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.

like image 166
jmj Avatar answered Sep 19 '22 17:09

jmj


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.

like image 27
Andy Avatar answered Sep 16 '22 17:09

Andy