Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList Find First and Last Element

Tags:

java

android

Good Evening,

I have an ArrayList (instantiated as ld_data) and I iterate forward and back looking / displaying to the user the element data. In this process I need to know when I am at the first element and the last. Detecting when I am at the last element I do as such:

if((index + 1) <= ld_data.size())
{
    ....
}

This works because the size property also is the upper bound of the ArrayList. However detecting when I am at the first element is not as easy for me. The best I've been able to figure out is this which seems rather lame....but it works.

if((index - 1) >= (ld_data.size() - ld_data.size()))
{
    ....
}

In the C# .NET world we have ArrayList.UpperBound or ArrayList.LowerBound is there something similiar in Java?

JB

EDIT: Further details. So for more information I am bound to a ListView. So when the user has scrolled to the first element of the list I want to show a msg "At start of list" and when they reach the end show "End of list". I know there is a scrollbar that makes this obvious I'm just trying to give an example of what I'm doing. So this check occurs in the "OnScroll" event.

like image 224
GPGVM Avatar asked Jun 07 '12 05:06

GPGVM


1 Answers

Its always advised to use Iterators or ListIterator to iterate through a list. Using the list size as reference does not workout when you are modifying the list data (removing or inserting elements).

Iterator - allow the caller to iterate through a list in one direction and remove elements from the underlying collection during the iteration with well-defined semantics

You can use a ListIterator to iterate through the list. A ListIterator allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. You can refer the below example.

ArrayList<String> list = new ArrayList<String>();
    ListIterator<String> iterator = list.listIterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next());
        ...
        ...
        System.out.println(iterator.previous());
        if(!iterator.hasPrevious()){
            System.out.println("at start of the list");
        }else if(!iterator.hasNext()){
            System.out.println("at end of the list");
        }

    }

This is just an example showing the usage of a ListIterator, please analyze what your requirement is and implement as required.

like image 140
Rakesh Avatar answered Oct 03 '22 17:10

Rakesh