Pregunta

¿Cómo puedo obtener el último valor de un objeto ArrayList?

No sé el último índice de ArrayList.

¿Fue útil?

Solución

La siguiente es parte de la List interfaz (que ArrayList implementa):

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

E es el tipo de elemento. Si la lista está vacía, get lanza una IndexOutOfBoundsException . Puede encontrar toda la documentación de la API aquí .

Otros consejos

No es una manera elegante de vainilla en Java.

Google guayaba

El biblioteca de Google guayaba es grande - echa un vistazo a su clase Iterables . Este método va a lanzar una NoSuchElementException si la lista está vacía, a diferencia de una IndexOutOfBoundsException , al igual que con el enfoque típico size()-1 - encuentro un NoSuchElementException mucho más agradable, o la capacidad de especificar un defecto:

lastElement = Iterables.getLast(iterableList);

También puede proporcionar un valor por defecto si la lista está vacía, en lugar de una excepción:

lastElement = Iterables.getLast(iterableList, null);

o, si está usando las opciones:

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

esto debe hacerlo:

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

Yo uso la clase de micro-util para conseguir la última (y primera) elemento de la lista:

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

Ligeramente más 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();
  }
}

El método size() devuelve el número de elementos en el ArrayList. Los valores del índice de los elementos se 0 través (size()-1), por lo que usarían myArrayList.get(myArrayList.size()-1) para recuperar el último elemento.

El uso de lambdas:

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

Si es posible, intercambiar el ArrayList para una ArrayDeque, que cuenta con métodos convenientes como removeLast.

Como se indica en la solución, si el List está vacía, entonces un IndexOutOfBoundsException es lanzada. Una solución mejor es usar el tipo 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));
    }
}

Como era de esperar, el último elemento de la lista se devuelve como un Optional:

var list = List.of(10, 20, 30);
assert ListUtils.last(list).orElse(-1) == 30;

También se ocupa de gracia con las listas vacías, así:

var emptyList = List.<Integer>of();
assert ListUtils.last(emptyList).orElse(-1) == -1;

Si utiliza una LinkedList en su lugar , usted puede acceder al primer elemento y el último con sólo getFirst() y getLast() (si desea un limpiador de manera que el tamaño() -1 y get(0))

La aplicación

Declarar una LinkedList

LinkedList<Object> mLinkedList = new LinkedList<>();

Luego de esto son los métodos que se pueden utilizar para conseguir lo que quieres, en este caso estamos hablando de PRIMERO y ÚLTIMA elemento de una lista

/**
     * 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);
    }

Así , entonces usted puede utilizar

mLinkedList.getLast(); 

para obtener el último elemento de la lista.

No hay elegante manera de conseguir el último elemento de una lista en Java (en comparación con, por ejemplo, items[-1] en Python).

Usted tiene que usar list.get(list.size()-1).

Cuando se trabaja con listas obtenidas mediante llamadas a métodos complicados, la solución radica en la variable temporal:

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

Esta es la única opción para evitar la versión fea y suelen ser caros o incluso no trabajar:

return someObject.someMethod(someArgument, anotherObject.anotherMethod()).get(
    someObject.someMethod(someArgument, anotherObject.anotherMethod()).size() - 1
);

Sería bueno si solución para este problema de diseño se introdujo a la API de Java.

El último elemento de la lista es list.size() - 1. La colección está respaldado por una matriz y matrices inicia en el índice 0.

Así elemento 1 en la lista está en el índice 0 en la matriz

Element 2 en la lista está en el índice 1 en el array

Element 3 en la lista está en el índice 2 en el array

y así sucesivamente ..

¿Qué tal esto .. En algún lugar de su clase ...

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

Si modifica su lista, a continuación, utilizar listIterator() e iterar desde el último índice (es decir size()-1 respectivamente). Si usted falla de nuevo, revisar su estructura de lista.

Todo lo que necesita hacer es el tamaño de su uso () para obtener el último valor de la Arraylist. Por ej. si ArrayList de números enteros, a continuación, obtener el último valor que tendrá que

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

Recuerde, los elementos de una Arraylist se puede acceder mediante valores de índice. Por lo tanto, ArrayLists se utilizan generalmente para buscar artículos.

matrices almacenan su tamaño en una variable local llamada 'longitud'. Dada una matriz denominada "a" se puede utilizar el siguiente para hacer referencia al último índice sin conocer el valor del índice

a [a.length-1]

para asignar un valor de 5 a este último índice se debería utilizar:

a [a.length-1] = 5;

Alternativa mediante la API Stream:

list.stream().reduce((first, second) -> second)

Los resultados de un facultativo del último elemento.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top