3 回答

慕斯王
TA贡献1864条经验 获得超2个赞
以下是List接口的一部分(由ArrayList实现):
E e = list.get(list.size() - 1);
E是元素类型。如果列表为空,则get抛出IndexOutOfBoundsException。您可以在此处找到整个API文档。

繁花如伊
TA贡献2012条经验 获得超12个赞
原始Java中没有一种优雅的方法。
谷歌番石榴
在谷歌番石榴库是伟大的-看看他们的Iterables阶级。NoSuchElementException如果列表为空,则此方法将抛出a ,而不是使用IndexOutOfBoundsException,与典型size()-1方法一样-我发现NoSuchElementException更好,或者可以指定默认值:
lastElement = Iterables.getLast(iterableList);
如果列表为空,还可以提供一个默认值,而不是一个异常:
lastElement = Iterables.getLast(iterableList, null);
或者,如果您使用的是选项:
lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
添加回答
举报
0/150
提交
取消