716

如何获取 ArrayList 的最后一个值?

我不知道 ArrayList 的最后一个索引。

4

23 回答 23

807

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

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

E是元素类型。如果列表为空,则get抛出IndexOutOfBoundsException. 您可以在此处找到完整的 API 文档。

于 2009-03-26T22:42:45.427 回答
232

香草 Java 中没有优雅的方式。

谷歌番石榴

Google Guava库很棒——看看他们的Iterables课程。如果列表为空,则此方法将抛出 a 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);
于 2012-12-28T16:16:04.163 回答
195

这应该这样做:

if (arrayList != null && !arrayList.isEmpty()) {
  T item = arrayList.get(arrayList.size()-1);
}
于 2009-03-26T22:41:29.970 回答
31

我使用 micro-util 类来获取列表的最后一个(也是第一个)元素:

public final class Lists {

    private Lists() {
    }

    public static <T> T getFirst(List<T> list) {
        return list != null && !list.isEmpty() ? list.get(0) : null;
    }

    public static <T> T getLast(List<T> list) {
        return list != null && !list.isEmpty() ? list.get(list.size() - 1) : null;
    }
}

稍微灵活一点:

import java.util.List;

/**
 * Convenience class that provides a clearer API for obtaining list elements.
 */
public final class Lists {

  private Lists() {
  }

  /**
   * Returns the first item in the given list, or null if not found.
   *
   * @param <T> The generic list type.
   * @param list The list that may have a first item.
   *
   * @return null if the list is null or there is no first item.
   */
  public static <T> T getFirst( final List<T> list ) {
    return getFirst( list, null );
  }

  /**
   * Returns the last item in the given list, or null if not found.
   *
   * @param <T> The generic list type.
   * @param list The list that may have a last item.
   *
   * @return null if the list is null or there is no last item.
   */
  public static <T> T getLast( final List<T> list ) {
    return getLast( list, null );
  }

  /**
   * Returns the first item in the given list, or t if not found.
   *
   * @param <T> The generic list type.
   * @param list The list that may have a first item.
   * @param t The default return value.
   *
   * @return null if the list is null or there is no first item.
   */
  public static <T> T getFirst( final List<T> list, final T t ) {
    return isEmpty( list ) ? t : list.get( 0 );
  }

  /**
   * Returns the last item in the given list, or t if not found.
   *
   * @param <T> The generic list type.
   * @param list The list that may have a last item.
   * @param t The default return value.
   *
   * @return null if the list is null or there is no last item.
   */
  public static <T> T getLast( final List<T> list, final T t ) {
    return isEmpty( list ) ? t : list.get( list.size() - 1 );
  }

  /**
   * Returns true if the given list is null or empty.
   *
   * @param <T> The generic list type.
   * @param list The list that has a last item.
   *
   * @return true The list is empty.
   */
  public static <T> boolean isEmpty( final List<T> list ) {
    return list == null || list.isEmpty();
  }
}
于 2014-10-10T14:49:26.253 回答
15

size()方法返回 ArrayList 中的元素数。元素的索引值是0through (size()-1),因此您将使用它myArrayList.get(myArrayList.size()-1)来检索最后一个元素。

于 2009-03-26T22:44:40.350 回答
7

使用 lambda:

Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 1);
于 2018-05-08T01:18:10.740 回答
7

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

你必须使用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,那就太好了。

于 2019-06-05T21:20:23.720 回答
5

如果可以的话,把 换成ArrayListArrayDeque它有方便的方法,比如removeLast.

于 2014-12-12T20:49:05.917 回答
4

如果您改用 LinkedList ,则可以使用 and 访问第一个元素和最后一个元素getFirst()getLast()如果您想要比 size() -1 和 get(0) 更简洁的方式)

执行

声明一个链表

LinkedList<Object> mLinkedList = new LinkedList<>();

然后这是您可以用来获得所需内容的方法,在这种情况下,我们正在讨论列表的FIRSTLAST元素

/**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    /**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }

所以,那么你可以使用

mLinkedList.getLast(); 

获取列表的最后一个元素。

于 2018-11-11T23:10:10.243 回答
4

如解决方案中所述,如果List为空,IndexOutOfBoundsException则抛出 an。更好的解决方案是使用以下Optional类型:

public class ListUtils {
    public static <T> Optional<T> last(List<T> list) {
        return list.isEmpty() ? Optional.empty() : Optional.of(list.get(list.size() - 1));
    }
}

如您所料,列表的最后一个元素以Optional:

var list = List.of(10, 20, 30);
assert ListUtils.last(list).orElse(-1) == 30;

它还可以优雅地处理空列表:

var emptyList = List.<Integer>of();
assert ListUtils.last(emptyList).orElse(-1) == -1;
于 2019-04-09T13:07:23.613 回答
4

考虑到空列表的一个班轮将是:

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

或者,如果您不喜欢 null 值(并且性能不是问题):

Optional<T> lastItem = list.stream().reduce((first, second) -> second);
于 2021-01-02T07:58:03.947 回答
2

如果你有一个 Spring 项目,你也可以使用CollectionUtils.lastElementfrom Spring ( javadoc ),所以你不需要像 Google Guava 那样添加额外的依赖。

它是 null 安全的,因此如果您传递 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)用于断言。

于 2020-08-21T12:01:20.420 回答
1

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

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

例如:

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

于 2020-01-13T09:09:32.897 回答
0

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

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

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

于 2020-04-09T19:42:09.930 回答
0

这对我有用。

private ArrayList<String> meals;
public String take(){
  return meals.remove(meals.size()-1);
}
于 2020-12-13T07:24:29.530 回答
-1

列表中的最后一项是list.size() - 1。该集合由一个数组支持,数组从索引 0 开始。

所以列表中的元素 1 位于数组中的索引 0

列表中的元素 2 在数组中的索引 1 处

列表中的元素 3 在数组中的索引 2 处

等等..

于 2015-11-25T11:28:17.423 回答
-3

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

于 2010-10-28T12:43:11.017 回答
-3

这个怎么样..在你班上的某个地方......

List<E> list = new ArrayList<E>();
private int i = -1;
    public void addObjToList(E elt){
        i++;
        list.add(elt);
    }


    public E getObjFromList(){
        if(i == -1){ 
            //If list is empty handle the way you would like to... I am returning a null object
            return null; // or throw an exception
        }

        E object = list.get(i);
        list.remove(i); //Optional - makes list work like a stack
        i--;            //Optional - makes list work like a stack
        return object;
    }
于 2014-12-12T23:48:33.433 回答
-4

您需要做的就是使用 size() 来获取 Arraylist 的最后一个值。例如。如果你是整数的 ArrayList,那么要获得最后一个值,你将不得不

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

请记住,可以使用索引值访问 Arraylist 中的元素。因此,ArrayLists 一般用于搜索项目。

于 2016-02-14T01:42:48.953 回答
-4

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

a[a.length-1]

要将值 5 分配给最后一个索引,您将使用:

a[a.length-1]=5;

于 2017-04-05T02:57:34.013 回答
-4

在 JavaScript 中获取 arraylist 的最后一个值:

var yourlist = ["1","2","3"];
var lastvalue = yourlist[yourlist.length -1];

它给出的输出为 3 。

于 2021-10-23T09:06:55.660 回答
-6

使用 Stream API 的替代方法:

list.stream().reduce((first, second) -> second)

结果是最后一个元素的 Optional。

于 2018-12-04T16:51:06.887 回答
-11

在 Kotlin 中,您可以使用以下方法last

val lastItem = list.last()
于 2019-09-08T02:41:30.110 回答