Java – ArrayList finds the first and last elements

Good evening,

I have an ArrayList (instantiated as ld_data), and I query / display element data forward and backward In this process, I need to know that I am in the first element and the last element Detect when I'm in the last element, I do this:

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

This is because the size attribute is also the upper limit of ArrayList However, it is not easy for me to detect the first element Best of all, I've been able to figure it out. It seems lame But its works

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

In C # Net world, we have ArrayList Upperbound or ArrayList Does Lowerbound have something similar in Java?

JB

Editor: more details So for more information, I bind to a listview So when the user scrolls to the first element of the list, I want to display an MSG "list start" and "end list" when they reach the end I know there is a scroll bar, which makes me very clear. I just want to give an example of what I'm doing So this check occurs in the "onscroll" event

Solution

It always recommends using iterators or listiterators to traverse the list When you modify list data (delete or insert elements), using the list size as a reference does not exercise

Iterator – allows the caller to traverse the list in one direction and delete elements from the underlying collection during the iteration, with well-defined semantics

You can use listiterator to traverse the list Listiterator allows the programmer to traverse the list in any direction, modify the list during iteration, and obtain the current position of the iterator in the list You can refer to the following examples

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 of using listiterator. Please analyze your requirements and implement them as needed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>