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


当前回答

guava提供了另一种从List中获取最后一个元素的方法:

last = Lists.reverse(list).get(0)

如果提供的列表为空,则抛出IndexOutOfBoundsException异常

其他回答

这应该做到:

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

在Java中没有获得列表的最后一个元素的优雅方法(与Python中的items[-1]相比)。

你必须使用list.get(list.size()-1)。

当处理由复杂方法调用获得的列表时,解决方法在于临时变量:

List<E> list = someObject.someMethod(someArgument, anotherObject.anotherMethod());
return list.get(list.size()-1);

这是避免丑陋且昂贵甚至无法工作的版本的唯一选择:

return someObject.someMethod(someArgument, anotherObject.anotherMethod()).get(
    someObject.someMethod(someArgument, anotherObject.anotherMethod()).size() - 1
);

如果能在Java API中引入对这个设计缺陷的修复,那就太好了。

数组将它们的大小存储在一个名为length的局部变量中。给定一个名为“a”的数组,您可以使用以下方法引用最后一个索引,而不需要知道索引值

(a.length-1)

要给最后一个索引赋值5,你可以使用:

[a.length-1] = 5;

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

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

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

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

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

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