Is there any better way to access the first and last locations on a Java list other than
curr.set(curr.size()-1, 10);
curr.get(curr.size()-1);
curr.set(0, 10);
curr.get(0);
where curr
is a List
?
If you use LinkedList
you can get the last and first elements.
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("element");
String last = linkedList.getLast();
String first = linkedList.getFirst();
Both operations are constant time, but a NoSuchElementException
will be thrown if the list is empty.