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 ?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With