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

时间:2022-11-27 11:33:56

How can I get the last value of an ArrayList?

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

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

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

13 个解决方案

#1


499  

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

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

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

E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.

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

#2


170  

this should do it:

这应该这样做:

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

#3


156  

There isn't an elegant way in vanilla Java.

在普通Java中没有一种优雅的方式。

Google Guava

The Google Guava library is great - check out their Iterables class. 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:

谷歌番石榴库非常棒——请查看它们的Iterables类。如果列表是空的,该方法将抛出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);

#4


22  

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

#5


9  

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

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

#6


4  

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

如果可以,可以将ArrayList替换为ArrayDeque, ArrayDeque有像removeLast这样方便的方法。

#7


1  

            Let ArrayList is myList

            public void getLastValue(List myList){
            // Check ArrayList is null or Empty
            if(myList == null || myList.isEmpty()){
                return;
            }

            // check size of arrayList
            int size = myList.size();


    // Since get method of Arraylist throws IndexOutOfBoundsException if index >= size of arrayList. And in arraylist item inserts from 0th index.
    //So please take care that last index will be (size of arrayList - 1)
            System.out.print("last value := "+myList.get(size-1));
        }

#8


0  

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..

等等. .

#9


0  

Using lambdas:

使用lambdas:

Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 1);

#10


-1  

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的最后一个值。对于exp,如果你排列整数的数组,那么为了得到最后的值,你必须

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中的元素。因此,arraylist通常用于搜索项目。

#11


-1  

arrays store their size in a local variable called 'length'. Given an array named "a" you could use the following to reference the last index without knowing the index value

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

a[a.length-1]

(a.length-1)

to assign a value of 5 to this last index you would use:

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

a[a.length-1]=5;

[a.length-1]= 5;

#12


-2  

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

#13


-3  

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

如果您修改了列表,那么使用listIterator()和迭代来自最后一个索引(分别是size()-1)。如果再次失败,请检查列表结构。

#1


499  

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

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

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

E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.

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

#2


170  

this should do it:

这应该这样做:

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

#3


156  

There isn't an elegant way in vanilla Java.

在普通Java中没有一种优雅的方式。

Google Guava

The Google Guava library is great - check out their Iterables class. 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:

谷歌番石榴库非常棒——请查看它们的Iterables类。如果列表是空的,该方法将抛出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);

#4


22  

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

#5


9  

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

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

#6


4  

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

如果可以,可以将ArrayList替换为ArrayDeque, ArrayDeque有像removeLast这样方便的方法。

#7


1  

            Let ArrayList is myList

            public void getLastValue(List myList){
            // Check ArrayList is null or Empty
            if(myList == null || myList.isEmpty()){
                return;
            }

            // check size of arrayList
            int size = myList.size();


    // Since get method of Arraylist throws IndexOutOfBoundsException if index >= size of arrayList. And in arraylist item inserts from 0th index.
    //So please take care that last index will be (size of arrayList - 1)
            System.out.print("last value := "+myList.get(size-1));
        }

#8


0  

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..

等等. .

#9


0  

Using lambdas:

使用lambdas:

Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 1);

#10


-1  

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的最后一个值。对于exp,如果你排列整数的数组,那么为了得到最后的值,你必须

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中的元素。因此,arraylist通常用于搜索项目。

#11


-1  

arrays store their size in a local variable called 'length'. Given an array named "a" you could use the following to reference the last index without knowing the index value

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

a[a.length-1]

(a.length-1)

to assign a value of 5 to this last index you would use:

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

a[a.length-1]=5;

[a.length-1]= 5;

#12


-2  

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

#13


-3  

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

如果您修改了列表,那么使用listIterator()和迭代来自最后一个索引(分别是size()-1)。如果再次失败,请检查列表结构。