如何获取 ArrayList 的最后一个值

新手上路,请多包涵

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

原文由 Jessy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 697
2 个回答

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

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

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

原文由 Johannes Schaub - litb 发布,翻译遵循 CC BY-SA 3.0 许可协议

普通 Java 中没有优雅的方式。

谷歌番石榴

Google Guava 库很棒 - 查看他们的 Iterables。 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 更好,或者指定默认值的能力:

 lastElement = Iterables.getLast(iterableList);

如果列表为空,您还可以提供默认值,而不是异常:

 lastElement = Iterables.getLast(iterableList, null);

或者,如果您使用的是选项:

 lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);

原文由 Antony Stubbs 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题