如何获取ArrayList的最后一个值

33 浏览
0 Comments

如何获取ArrayList的最后一个值

如何获取ArrayList的最后一个值?

admin 更改状态以发布 2023年5月23日
0
0 Comments

在纯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);

0
0 Comments

以下是List接口的一部分(ArrayList实现了该接口):

E e = list.get(list.size() - 1);

E是元素类型。如果列表为空,get会抛出IndexOutOfBoundsException。您可以在这里找到完整的API文档。

0