Java获取集合的最后一个元素 [英] Java get last element of a collection

查看:3837
本文介绍了Java获取集合的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合,我想获得集合的最后一个元素。

I have a collection, I want to get the last element of the collection. What's the most straighforward and fast way to do so?

一个解决方案是先使用toArray(),然后返回数组的最后一个元素。是否还有其他更好的?

One solution is to first toArray(), and then return the last element of the array. Is there any other better ones?

推荐答案

A 集合必须有序的元素集合,因此可能不存在最后元素的概念。如果你想要一个有序的,你可以使用 SortedSet ,它有一个 last()方法。或者您可以使用列表并调用 mylist.get(mylist.size() - 1);

A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

如果你真的需要最后一个元素,你应该使用列表 SortedSet 。但如果你有一个 Collection ,你真的,真的,真的需要最后一个元素,你可以使用 toArray ,或者您可以使用迭代器并迭代到列表的末尾。例如:

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray or you could use an Iterator and iterate to the end of the list. For example:

public Object getLastElement(final Collection c) {
    final Iterator itr = c.iterator();
    Object lastElement = itr.next();
    while(itr.hasNext()) {
        lastElement=itr.next();
    }
    return lastElement;
}

这篇关于Java获取集合的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆