|
Get the last element in a java.util.List |
|
Facts -
Java
|
|
Wednesday, 14 July 2010 21:10 |
|
This article discusses aspects of the java.util.List interface with java version 5 and 6 in mind.
The interface java.util.List does not have a method getLast() to get the last element in the list. Sometimes it is possible to use the LinkedList class instead of using the List interface. The LinkedList class implements both the List interface and the Deque interface. The latter interface offers a method getLast().
Otherwise one can iterate through the list to get the last element:
// this code has not been not tested
T getLast(List<T> l)
{
for(T elem:l) {
lastelem = elem;
}
return lastelem;
}
However a better solution is to get the last element by using the size and get methods:
T getLast(List<T> l) { return l.get(l.size() -1); }
|