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


当前回答

这对我很管用。

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将返回数组的最后一个元素。

如果可以的话,将ArrayList替换为ArrayDeque,它有方便的方法,如removeLast。

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

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

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

如果你使用LinkedList代替,你可以通过getFirst()和getLast()访问第一个元素和最后一个元素(如果你想要一个比size() -1和get(0)更干净的方式)

实现

声明一个LinkedList

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

然后这是你可以用来得到你想要的东西的方法,在这种情况下,我们谈论的是列表的FIRST和LAST元素

/**
     * 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(); 

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

使用流API的替代方案:

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

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