Как получить последнее значение ArrayList

Как я могу получить последнее значение ArrayList?

Я не знаю последнего индекса ArrayList.

13 ответов


следующая часть List интерфейс (который реализует ArrayList):

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

E тип элемента. Если список пуст,get выдает IndexOutOfBoundsException. Вы можете найти всю документацию API здесь.


это должно сделать это:

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

в vanilla Java нет элегантного способа.

Google Guava

The Google Guava библиотека отличная-проверьте их Iterables класс. Этот метод будет бросать NoSuchElementException если список пуст, в отличие от IndexOutOfBoundsException, как с типичными size()-1 подход - я найти NoSuchElementException гораздо приятнее, или возможность указать значение по умолчанию:

lastElement = Iterables.getLast(iterableList);

вы также можете указать значение по умолчанию если список пуст, вместо исключения:

lastElement = Iterables.getLast(iterableList, null);

или, если вы используете параметры:

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

Я использую класс 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;
    }
}

немного более гибкий:

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

на size() метод возвращает количество элементов в коллекции. Значения Индекса элементов:0 через (size()-1), Так что вы должны использовать myArrayList.get(myArrayList.size()-1) для получения последнего элемента.


Если можете, замените ArrayList на ArrayDeque, который имеет удобные методы, такие как removeLast.


использование lambdas:

Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 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));
        }

последний элемент списка list.size() - 1. Коллекция поддерживается массивом, а массивы начинаются с индекса 0.

таким образом, элемент 1 в списке имеет индекс 0 в массиве

Элемент 2 в списке имеет индекс 1 в массиве

элемент 3 в списке имеет индекс 2 в массиве

и так далее..


все, что вам нужно сделать, это использовать size (), чтобы получить последнее значение Arraylist. Для экс. если вы ArrayList целых чисел, то для получения последнего значения вам придется

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

помните, что к элементам в Arraylist можно получить доступ, используя значения Индекса. Поэтому ArrayLists обычно используются для поиска элементов.


массивы хранят свой размер в локальной переменной под названием 'length'. Учитывая массив с именем "a", вы можете использовать следующее Для ссылки на последний индекс, не зная значения Индекса

a[a.длина-1]

чтобы присвоить значение 5 этому последнему индексу, вы должны использовать:

a[a.длина-1]=5;


Как насчет этого.. Где-то в твоем классе...

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

Если вы измените свой список, используйте listIterator() и итерация из последнего индекса (то есть size()-1 соответственно). Если вы снова потерпите неудачу, проверьте структуру списка.