如何获取数组列表的最后一个值?


当前回答

这应该做到:

if (arrayList != null && !arrayList.isEmpty()) {
  T item = arrayList.get(arrayList.size()-1);
}

其他回答

这应该做到:

if (arrayList != null && !arrayList.isEmpty()) {
  T item = arrayList.get(arrayList.size()-1);
}

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

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

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

在普通Java中没有优雅的方法。

谷歌番石榴

谷歌番石榴库是伟大的-检查他们的Iterables类。如果列表为空,这个方法将抛出NoSuchElementException,而不是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);

如果修改列表,则使用listIterator()并从最后一个索引(即分别为size()-1)开始迭代。 如果你再次失败,检查你的列表结构。

你所需要做的就是使用size()来获取数组列表的最后一个值。 例如,如果你是整数的数组列表,那么为了得到最后一个值,你必须

int lastValue = arrList.get(arrList.size()-1);

记住,数组列表中的元素可以通过下标值访问。因此,数组列表通常用于搜索项。