Java address list for first and last item

Is there a better way to access the first and last locations in a java list other than

curr.set(curr.size()-1, 10);
curr.get(curr.size()-1);
curr.set(0, 10);
curr.get(0);

      

Here you can read the list.

+3


source to share


3 answers


If you are using LinkedList

, you can get the last and first items.

LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("element");

String last = linkedList.getLast();
String first = linkedList.getFirst();

      



Both operations are constant time, but NoSuchElementException

will be selected if the list is empty.

+4


source


I would rather use Google Guava to Iterables

use a class ;

Iterables.getFirst(myList);
Iterables.getLast(myList);

      



Also, it has safe logic where you can specify a default if the list is empty / null.

Iterables.getFirst(myList, defaultVal);
Iterables.getLast(myList, defaultVal);

      

+2


source


In the event that the first and last are the only elements you are actually accessing, I would suggest using java.util.Deque<T>

instead List

.

0


source







All Articles