如何获取数组列表的最后一个值?
当前回答
数组将它们的大小存储在一个名为length的局部变量中。给定一个名为“a”的数组,您可以使用以下方法引用最后一个索引,而不需要知道索引值
(a.length-1)
要给最后一个索引赋值5,你可以使用:
[a.length-1] = 5;
其他回答
下面是List接口的一部分(由ArrayList实现):
E e = list.get(list.size() - 1);
E是元素类型。如果列表为空,get抛出IndexOutOfBoundsException异常。你可以在这里找到完整的API文档。
如果你使用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();
来获取列表的最后一个元素。
考虑空列表的一行代码如下:
T lastItem = list.size() == 0 ? null : list.get(list.size() - 1);
或者如果你不喜欢空值(性能不是问题):
Optional<T> lastItem = list.stream().reduce((first, second) -> second);
在Java中没有获得列表的最后一个元素的优雅方法(与Python中的items[-1]相比)。
你必须使用list.get(list.size()-1)。
当处理由复杂方法调用获得的列表时,解决方法在于临时变量:
List<E> list = someObject.someMethod(someArgument, anotherObject.anotherMethod());
return list.get(list.size()-1);
这是避免丑陋且昂贵甚至无法工作的版本的唯一选择:
return someObject.someMethod(someArgument, anotherObject.anotherMethod()).get(
someObject.someMethod(someArgument, anotherObject.anotherMethod()).size() - 1
);
如果能在Java API中引入对这个设计缺陷的修复,那就太好了。
使用流API的替代方案:
list.stream().reduce((first, second) -> second)
结果为最后一个元素的Optional。
推荐文章
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 如何在POM.xml中引用环境变量?