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


当前回答

由于数组列表中的索引从0开始,并在实际大小前一位结束,因此返回最后一个数组列表元素的正确语句将是:

Int last = mylist.get(mylist.size()-1);

例如:

如果数组列表的大小为5,那么size-1 = 4将返回数组的最后一个元素。

其他回答

在Kotlin中,你可以使用最后的方法:

val lastItem = list.last()

这应该做到:

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

如果您有一个Spring项目,您也可以使用CollectionUtils。因此,您不需要添加额外的依赖项,如谷歌Guava。

它是空安全的,所以如果你传递null,你只会收到null返回。但是在处理响应时要小心。

下面是一些单元测试来演示它们:

@Test
void lastElementOfList() {
    var names = List.of("John", "Jane");

    var lastName = CollectionUtils.lastElement(names);

    then(lastName)
        .as("Expected Jane to be the last name in the list")
        .isEqualTo("Jane");
}

@Test
void lastElementOfSet() {
    var names = new TreeSet<>(Set.of("Jane", "John", "James"));

    var lastName = CollectionUtils.lastElement(names);

    then(lastName)
        .as("Expected John to be the last name in the list")
        .isEqualTo("John");
}

注意:org.assertj.core.api.BDDAssertions#then(java.lang.String)用于断言。

这对我很管用。

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

由于数组列表中的索引从0开始,并在实际大小前一位结束,因此返回最后一个数组列表元素的正确语句将是:

Int last = mylist.get(mylist.size()-1);

例如:

如果数组列表的大小为5,那么size-1 = 4将返回数组的最后一个元素。