How to acces previous element in an ArrayList using "this"

91 views Asked by At

I would like to access previous element from the reserved name "this" like that :

paper.lines.get(this-1);

Is there a way to do it simply?

1

There are 1 answers

1
Eran On BEST ANSWER

If this is an element in the List and you want the elements located before it, you need :

paper.lines.get(paper.lines.indexOf(this) - 1);

Of course this code lacks validations, since this may not be found in the List, or it may be the first element of the List. In both cases you'll get an exception.

So, safer code would be:

int index = paper.lines.indexOf(this);
if (index > 0) {
    return paper.lines.get(index - 1);
}