14

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.

GPGVM
  • 5,515
  • 10
  • 56
  • 97

9 Answers9

14

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.

Rakesh
  • 4,264
  • 4
  • 32
  • 58
10
List<YourData> list = new ArrayList<YourData>();

for(int index=0; index < list.size(); index++) {

    YourData currElement = list.get(index);

    if(index == 0) {
        //currElement is the first element
    }

    if(index == list.size() - 1) {
         //currElement is the last element
    }
}
MKJParekh
  • 34,073
  • 11
  • 87
  • 98
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • -1 BUG : if size is 0 then first element will be zero and there will be no last element found, and the for loop is unnecessary for this. – MKJParekh Jun 07 '12 at 06:30
  • @FasteKerinns: Well, if the size is 0 then `index – Bhesh Gurung Jun 07 '12 at 06:41
  • yes you are right, sorry for that I missed "<", taking back my down vote, but still i would say, no need for loop. [had to edit to vote again] – MKJParekh Jun 07 '12 at 06:47
  • I like your idea also. That way you will have the reference to the first and last element(s). I just used the loop because that's what the OP seems to be doing. – Bhesh Gurung Jun 07 '12 at 06:49
2

I would suggest you to use Google Guava for that. The getLast method will throw NoSuchElementException if the list is empty:

lastElement = Iterables.getLast(iterableList);

And to get the first element:

firstElement = Iterables.getFirst(iterable, defaultValue)

For more information about Java Collections, check it out.

Johnny
  • 14,397
  • 15
  • 77
  • 118
1

Just check if the index is equal to 0. The first element always resides in this index.

Dhruv Gairola
  • 9,102
  • 5
  • 39
  • 43
1

ArrayLists always have a bottom index of 0. So if (index > 0) { // okay to decrement } will work fine.

You can also request a list iterator

ListIterator<Item> i = ld_data.listIterator();

if (i.hasNext()) {
    Item item = i.next();
}

// and

if (i.hasPrevious()) {
    Item item = i.previous();
}
Gene
  • 46,253
  • 4
  • 58
  • 96
1

It appears you want to abstract away the logic to deal with the first, last, and anything that comes in between in different ways.

You can do it by defining a destructuring class as shown below:

import java.util.*;

abstract class EndsDestructurer<A, B> {
  public abstract B first(A a);
  public abstract B intermediate(A a);
  public abstract B last(A a);

  public List<B> apply(List<A> xs) {
    int i = 0;
    int lastIndex = xs.size() - 1;
    List<B> ys = new ArrayList<B>();
    for (A x : xs) {
      if (i == 0) ys.add(first(x));
      else if (i == lastIndex) ys.add(last(x));
      else ys.add(intermediate(x));
      i++;
    }
    return ys;
  }
}

Use:

EndsDestructurer<Object, String> stringer = 
  new EndsDestructurer<Object, String>() {
    public String first(Object o) { return "first: " + o; }
    public String intermediate(Object o) { return "intermediate: " + o; }
    public String last(Object o) { return "last: " + o; }
  };

List<Object> xs = Arrays.<Object>asList(90, "hello", 5.6, 12, "namaste", false);
System.out.println(stringer.apply(xs));

The above prints:
[first: 90, intermediate: hello, intermediate: 5.6, intermediate: 12, intermediate: namaste, last: false].

missingfaktor
  • 90,905
  • 62
  • 285
  • 365
0

Your index is always going to be 0 - myList.size() -1. I suspect maybe I'm not understanding your question because this seems self evident.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236
0

AFAIK, ArrayList class have no such method to give the first and last element of it's object.


You can write some code like,

ArrayList<String> arr = new ArrayList<String>();
int size = arr.size();
if(size==0)
{
    // no data
}
else if(size == 1)
{
    // first = arr.get(0);
    // last = arr.get(0);
}
else
{
    // first = arr.get(0);
    // last = arr.get(size-1);
}
MKJParekh
  • 34,073
  • 11
  • 87
  • 98
0

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

In the Java world, the first element of any indexable collection always has offset zero, so "lower bound" and "upper bound" methods would be redundant.

Just use the constant 0.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • They're redundant in C# too, but they're provided for convenience. – missingfaktor Jun 07 '12 at 06:49
  • Actually, by my reading of the online docs (http://msdn.microsoft.com/en-us/library/system.collections.arraylist%28v=vs.110%29.aspx) ArrayList *doesn't* have these methods at all. – Stephen C Jun 07 '12 at 09:24