The following is part of the List interface (which ArrayList implements):
E e = list.get(list.size() - 1);
E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.
The following is part of the List interface (which ArrayList implements):
E e = list.get(list.size() - 1);
E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.
There isn't an elegant way in vanilla Java prior to Java 21.
Google Guava
The Google Guava library is great - check out their Iterables.getLast() method. This method will throw a NoSuchElementException if the list is empty, as opposed to an IndexOutOfBoundsException, as with the typical size()-1 approach - I find a NoSuchElementException much nicer, or the ability to specify a default:
lastElement = Iterables.getLast(iterableList);
You can also provide a default value if the list is empty, instead of an exception:
lastElement = Iterables.getLast(iterableList, null);
or, if you're using Options:
lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
API bloat is probably the answer. From my experience the only time I've needed this functionality a Queue or Stack was the correct data structure for the job having the appropriate method.
a last() method is just as easy as list.get(list.size()-1), just like there is no first() method or fifth() method. It isn't that hard to synthesize and is a specialization. You can also reverse() the list and list.get(0) which will give the last item. Things that are easy to do, usually don't get their own specialized methods.
import java.util.ArrayList;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
final List<String> l = new ArrayList<String>();
l.add("A");
l.add("B");
l.add("Z");
System.out.println("l.get(0) = " + l.get(0));
System.out.println("l.get(l.size()-1) = " + l.get(l.size() - 1));
}
}
results in the following output
l.get(0) = A
l.get(l.size()-1) = Z
it is also presumptuous to assume that everything that implements the List interface actually has the concept of last() anything.