[java] ArrayList의 마지막 값을 얻는 방법

ArrayList의 마지막 값을 어떻게 얻을 수 있습니까?

ArrayList의 마지막 색인을 모르겠습니다.



답변

다음은 List인터페이스 (ArrayList가 구현하는)의 일부입니다 .

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

E요소 유형입니다. 목록이 비어 get있으면를 던집니다 IndexOutOfBoundsException. 전체 API 설명서는 여기에서 찾을 수 있습니다 .


답변

바닐라 자바에는 우아한 방법이 없습니다.

구글 구아바

구글 구아바 라이브러리는 중대하다 – 자신의 체크 아웃 Iterables클래스를 . 이 방법은 일반적인 접근 방식 과 NoSuchElementException마찬가지로 목록이 비어 있는 경우 를 던집니다. 훨씬 더 좋 거나 기본값을 지정하는 기능이 있습니다.IndexOutOfBoundsExceptionsize()-1NoSuchElementException

lastElement = Iterables.getLast(iterableList);

예외 대신 목록이 비어있는 경우 기본값을 제공 할 수도 있습니다.

lastElement = Iterables.getLast(iterableList, null);

또는 옵션을 사용하는 경우 :

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


답변

이 작업을 수행해야합니다.

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


답변

목록의 마지막 (그리고 첫 번째) 요소를 얻기 위해 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()메소드는 ArrayList의 요소 수를 리턴합니다. 요소의 색인 값은 0through (size()-1)이므로 myArrayList.get(myArrayList.size()-1)마지막 요소를 검색하는 데 사용 합니다.


답변

람다 사용 :

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


답변

당신이 할 수있는 경우를 교환 ArrayList위해 ArrayDeque같은 편리한 방법을 가지고있는 removeLast.