如何获取ArrayList的最后一个值

本文讨论了如何在Java中获取ArrayList的最后一个值,特别提到了使用Google Guava库的ListIterators类来优雅地实现这一操作。同时,文章提供了不同情况下的解决方案,包括处理空列表和提供默认值的选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:How to get the last value of an ArrayList

How can I get the last value of an ArrayList? 如何获取ArrayList的最后一个值?

I don't know the last index of the ArrayList. 我不知道ArrayList的最后一个索引。


#1楼

参考:https://stackoom.com/question/2sw5/如何获取ArrayList的最后一个值


#2楼

There isn't an elegant way in vanilla Java. 在香草Java中没有一种优雅的方式。

Google Guava 谷歌番石榴

The Google Guava library is great - check out their Iterables class . Google Guava库很棒 - 查看他们的Iterables This method will throw a NoSuchElementException if the list is empty, as opposed to an IndexOutOfBoundsException , as with the typical size()-1 approach - I find a NoSuchElementException much nicer, or the ability to specify a default: 如果列表为空,此方法将抛出NoSuchElementException ,而不是IndexOutOfBoundsException ,与典型的size()-1方法一样 - 我发现NoSuchElementException更好,或者指定默认值的能力:

lastElement = Iterables.getLast(iterableList);

You can also provide a default value if the list is empty, instead of an exception: 如果列表为空,您还可以提供默认值,而不是例外:

lastElement = Iterables.getLast(iterableList, null);

or, if you're using Options: 或者,如果您使用选项:

lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);

#3楼

I use micro-util class for getting last (and first) element of list: 我使用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;
    }
}

Slightly more flexible: 稍微灵活一点:

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();
  }
}

#4楼

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


#5楼

How about this.. Somewhere in your class... 怎么样......你班上的某个地方......

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;
    }

#6楼

The last item in the list is list.size() - 1 . 列表中的最后一项是list.size() - 1 The collection is backed by an array and arrays start at index 0. 该集合由数组支持,数组从索引0开始。

So element 1 in the list is at index 0 in the array 因此列表中的元素1位于数组中的索引0处

Element 2 in the list is at index 1 in the array 列表中的元素2位于数组中的索引1处

Element 3 in the list is at index 2 in the array 列表中的元素3位于数组中的索引2处

and so on.. 等等..

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值