如何获取ArrayList的最后一个值
在纯Java中没有优雅的方式。
Google Guava
Google Guava库非常好用-请查看他们的Iterables
类。这个方法会抛出NoSuchElementException
(如果列表为空),而不是像典型的size()-1
方法那样抛出IndexOutOfBoundsException
。我觉得NoSuchElementException
更好,或者您可以指定一个默认值:
lastElement = Iterables.getLast(iterableList);
如果列表为空,您也可以提供一个默认值,而不是抛出异常:
lastElement = Iterables.getLast(iterableList, null);
或者,如果您正在使用Options:
lastElementRaw = Iterables.getLast(iterableList, null); lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
以下是List接口的一部分(ArrayList实现了该接口):
E e = list.get(list.size() - 1);
E
是元素类型。如果列表为空,get
会抛出IndexOutOfBoundsException
。您可以在这里找到完整的API文档。