如何获取数组列表的最后一个值?
当前回答
使用lambdas:
Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 1);
其他回答
如果修改列表,则使用listIterator()并从最后一个索引(即分别为size()-1)开始迭代。 如果你再次失败,检查你的列表结构。
在普通Java中没有优雅的方法。
谷歌番石榴
谷歌番石榴库是伟大的-检查他们的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);
这对我很管用。
private ArrayList<String> meals;
public String take(){
return meals.remove(meals.size()-1);
}
如果你使用LinkedList代替,你可以通过getFirst()和getLast()访问第一个元素和最后一个元素(如果你想要一个比size() -1和get(0)更干净的方式)
实现
声明一个LinkedList
LinkedList<Object> mLinkedList = new LinkedList<>();
然后这是你可以用来得到你想要的东西的方法,在这种情况下,我们谈论的是列表的FIRST和LAST元素
/**
* 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);
}
然后你就可以用
mLinkedList.getLast();
来获取列表的最后一个元素。
size()方法返回数组列表中元素的个数。元素的下标值从0到(size()-1),因此可以使用myArrayList.get(myArrayList.size()-1)来检索最后一个元素。
推荐文章
- 使用split("|")按管道符号拆分Java字符串
- 当内存不足导致抛出OutOfMemoryError时会发生什么?
- 检查ArrayList中是否存在值
- 我们能在Java中创建无符号字节吗
- 同步vs锁定
- 在ExecutorService的提交和执行之间进行选择
- 如何在javadoc中转义@字符?
- 如何在Java中创建唯一的ID ?
- 为什么Java类的编译与空行不同?
- Android Studio无法找到有效的Jvm(与MAC OS相关)
- 为什么一个组合器需要减少方法转换类型在java 8
- CountDownLatch是如何在Java多线程中使用的?
- 如果我同步了同一个类上的两个方法,它们能同时运行吗?
- 如何减去X天从一个日期对象在Java?
- Java标识符中的“连接字符”是什么?