如何获取ArrayList的最后一个值

Jes*_*ssy 551 java arraylist

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

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

Joh*_*itb 639

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

E e = list.get(list.size() - 1);
Run Code Online (Sandbox Code Playgroud)

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

  • 不行.如果列表为空,list.size()将返回0.并且您将以list.get(-1)结束; (22认同)
  • @feresr呵呵.他想获得列表中的最后一个值.当然,这意味着size()> 0.对于任何类型的实现都是如此.阅读到最后将节省您编写评论所需的时间和我回答的时间:)我的答案在最后说*"如果列表为空,则抛出IndexOutOfBoundsException"* (15认同)
  • @Brady它不会导致ArrayList的O(n)迭代,因为你可以猜测,它是由数组支持的.因此,简单的get(<index>)只会导致从数组中进行恒定时间检索.(JDK源确认了这一点)对于其他列表实现,这不能保证,因此例如,LinkedList具有一个恒定时间的getLast()方法. (13认同)
  • 这会导致列表的迭代吗?这对我来说似乎并不高效.我来自C++,其中列表对象上有实际的front()和back()方法,这些方法在内部使用头部和尾部引用实现.Java中是否有类似的机制? (5认同)
  • 我不明白为什么他们决定为他们的`Vector`实现一个简单的`lastElement()`方法,而不是为`ArrayList`.这种不一致是怎么回事? (5认同)
  • @sherrellbc它会做同样的事情.如果Java有这个功能,它可以节省我打字的时间. (3认同)
  • 我用谷歌搜索了这个,因为我的大脑说“一定有一个更简单的方法”。Java 开始给人一种低级的感觉。 (2认同)
  • `list.get(list.size() - )`工作还是不起作用? (2认同)

Ant*_*bbs 198

在香草Java中没有一种优雅的方式.

谷歌番石榴

谷歌番石榴库是伟大的-看看他们的Iterables阶级.NoSuchElementException如果列表为空,此方法将抛出一个,而不是IndexOutOfBoundsException像典型size()-1方法那样 - 我发现NoSuchElementException更好,或者指定默认值的能力:

lastElement = Iterables.getLast(iterableList);
Run Code Online (Sandbox Code Playgroud)

如果列表为空,您还可以提供默认值,而不是例外:

lastElement = Iterables.getLast(iterableList, null);
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用选项:

lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
Run Code Online (Sandbox Code Playgroud)

  • 你应该添加`Iterables.getLast`来检查是否实现了`RandomAccess`,因此它是否访问O(1)中的项. (6认同)
  • @BillMan在HashSet的情况下是的,在ArrayList的情况下没有. (5认同)
  • 你知道这个方法是否在列表中进行线性遍历以找到最后一个元素吗? (3认同)
  • 你可以使用原生 Java 的 `Optional` 代替 `Option`。它也会更简洁一些:`lastElement = Optional.ofNullable(lastElementRaw);`。 (2认同)

Hen*_*aul 185

这应该这样做:

if (arrayList != null && !arrayList.isEmpty()) {
  T item = arrayList.get(arrayList.size()-1);
}
Run Code Online (Sandbox Code Playgroud)

  • 有没有光滑的方式去做?:/ (27认同)
  • 您应该至少演示如何分配它... ArrayList.get是副作用免费的. (6认同)
  • 表明上面没有分配/返回任何东西是否太小了? (2认同)
  • @hasnain_ahmad,当ArraList具有1个元素时,它可以正常工作,您应该担心未初始化的ArrayList和ArrayList的记录为零。这个答案可以处理两种情况 (2认同)

use*_*153 27

我使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

稍微灵活一点:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @ClickUpvote在一些小方法中使用Guava在很多情况下都是一种过度杀伤力.我的答案是寻找_vanilla Java解决方案_的人.如果您已在项目中使用Guava,请参阅基于Guava的解决方案的其他答案. (14认同)
  • 只需使用番石榴.不要重新发明 (8认同)
  • 如果你*不使用guava,你最终会编写很多像这样的实用程序类. (5认同)
  • 有时,获得添加第三方库的权限比添加单个本机Java类要多得多.例如,政府合同限制和筛选第三方图书馆. (5认同)
  • isEmpty不检查列表是否为空,因此应该为isNullOrEmpty,这不是问题的一部分-您尝试增强答案集或提供实用程序类(这是一种重新发明) 。 (2认同)

M. *_*tin 13

List#getLast

getLast从Java 21开始,可以使用list的方法。这将返回列表的最后一项,NoSuchElementException如果列表为空则抛出 a 。

list.getLast();
Run Code Online (Sandbox Code Playgroud)

  • OMG为此等了10年 (4认同)

Ken*_*aul 10

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


Tre*_*reg 7

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

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

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

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

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

return someObject.someMethod(someArgument, anotherObject.anotherMethod()).get(
    someObject.someMethod(someArgument, anotherObject.anotherMethod()).size() - 1
);
Run Code Online (Sandbox Code Playgroud)

如果将此设计缺陷的修复引入 Java API,那就太好了。

  • @DorianGray 从列表中读取最后一个元素是一个非常常见的操作,“list.get(list.size()-1)”是显示该问题的最小示例。我同意“高级”示例可能存在争议,并且可能是边缘案例,我只是想展示该问题如何进一步传播。我们假设“someObject”类是外来的,来自外部库。 (3认同)

Col*_*ame 6

正如解决方案中所述,如果为空,则抛出Listan 。IndexOutOfBoundsException更好的解决方案是使用以下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));
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所期望的,列表的最后一个元素以以下形式返回Optional

var list = List.of(10, 20, 30);
assert ListUtils.last(list).orElse(-1) == 30;
Run Code Online (Sandbox Code Playgroud)

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

var emptyList = List.<Integer>of();
assert ListUtils.last(emptyList).orElse(-1) == -1;
Run Code Online (Sandbox Code Playgroud)


Pim*_*oek 6

如果您有 Spring 项目,您还可以使用CollectionUtils.lastElementSpring ( 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");
}
Run Code Online (Sandbox Code Playgroud)

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


Joh*_*yer 5

如果可以的话,将换ArrayListArrayDeque,可以使用方便的方法,例如removeLast


小智 5

使用lambdas:

Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 1);
Run Code Online (Sandbox Code Playgroud)


Gas*_*lén 5

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

执行

声明一个链表

LinkedList<Object> mLinkedList = new LinkedList<>();
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用这些方法来获取所需的内容,在本例中,我们讨论的是列表的第一个最后一个元素

/**
     * 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);
    }
Run Code Online (Sandbox Code Playgroud)

那么,那么你可以使用

mLinkedList.getLast(); 
Run Code Online (Sandbox Code Playgroud)

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