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


当前回答

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

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

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

其他回答

这对我很管用。

private ArrayList<String> meals;
public String take(){
  return meals.remove(meals.size()-1);
}

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

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

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

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

这应该做到:

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

考虑空列表的一行代码如下:

T lastItem = list.size() == 0 ? null : list.get(list.size() - 1);

或者如果你不喜欢空值(性能不是问题):

Optional<T> lastItem = list.stream().reduce((first, second) -> second);