Java common utilities to get list size and last object
Even if it'开发者_高级运维s easy to make an handle make, but I wonder if there is any famous helper help to get the size of a list or to get the last object of a list. I think it is really a popular requirements, but I couldn't found one.
size = list==null? 0: list.size();
lastObject = isEmpty(list)? null:list.get(list.size() - 1).
Thanks,
Those don't seem all that helpful to me. I try to initialize my lists so they're not null, so the first one is not useful at all. As for the second, it's no more useful to get back a possibly-null object (which then has to be tested to see if it's null) than it is to check the size of the list first.
There isn't a helper method for this AFAIK. One thing you should make sure is that when writing your own helper utility, pay special attention to your target collection. If it is a List
, avoid using get(index)
since it is not very efficient for a linked list implementation. If it is an ArrayList
or in general any collection which implements RandomAccess
, get
is very efficient. The most generic way would be to obtain an iterator for the last element and invoke next()
on it if it exists.
public static <T> T getLast(final List<T> list) {
final ListIterator<T> listIterator = list.listIterator(list.size());
return listIterator.hasPrevious() ? listIterator.previous() : null;
}
Google Guava has a getLast method. However, I couldn't find a size method that handles null Collections.
精彩评论