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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/687833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:57:17  来源:igfitidea点击:

How to get the last value of an ArrayList

javaarraylist

提问by Jessy

How can I get the last value of an ArrayList?

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

I don't know the last index of the ArrayList.

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

采纳答案by Johannes Schaub - litb

The following is part of the Listinterface (which ArrayList implements):

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

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

Eis the element type. If the list is empty, getthrows an IndexOutOfBoundsException. You can find the whole API documentation here.

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

回答by Henrik Paul

this should do it:

这应该这样做:

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

回答by Ken Paul

The size()method returns the number of elements in the ArrayList. The index values of the elements are 0through (size()-1), so you would use myArrayList.get(myArrayList.size()-1)to retrieve the last element.

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

回答by dae

If you modify your list, then use listIterator()and iterate from last index (that is size()-1respectively). If you fail again, check your list structure.

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

回答by Antony Stubbs

There isn't an elegant way in vanilla Java.

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

Google Guava

谷歌番石榴

The Google Guavalibrary is great - check out their Iterablesclass. This method will throw a NoSuchElementExceptionif the list is empty, as opposed to an IndexOutOfBoundsException, as with the typical size()-1approach - I find a NoSuchElementExceptionmuch nicer, or the ability to specify a default:

谷歌番石榴库是伟大的-看看他们的Iterables阶级NoSuchElementException如果列表为空,则此方法将抛出 a ,而不是 an 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);

回答by user11153

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

回答by John Glassmyer

If you can, swap out the ArrayListfor an ArrayDeque, which has convenient methods like removeLast.

如果可以,换掉ArrayListfor an ArrayDeque,它有像removeLast.

回答by rokrfellr

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

回答by MircoProgram

The last item in the list is list.size() - 1. The collection is backed by an array and arrays start at index 0.

列表中的最后一项是list.size() - 1。该集合由一个数组支持,数组从索引 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..

等等..

回答by user4660857

All you need to do is use size() to get the last value of the Arraylist. For ex. if you ArrayList of integers, then to get last value you will have to

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

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

Remember, elements in an Arraylist can be accessed using index values. Therefore, ArrayLists are generally used to search items.

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