java 获取 LinkedHashSet 的最后一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14024022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting last of LinkedHashSet
提问by James Raitsev
I'd like to store a list of numbers 1,2,3,4 - (lets start with List<Integer>
)
我想存储数字 1,2,3,4 的列表 - (让我们开始List<Integer>
)
I'd like to make sure numbers are unique (ok, fine, Set<Integer>
)
我想确保数字是唯一的(好的,很好,Set<Integer>
)
I'd like to guarantee order (ok ... LinkedHashSet<Integer>
)
我想保证订单(好的... LinkedHashSet<Integer>
)
I'd like to get the last element from the list ..
我想从列表中获取最后一个元素..
What would be the simplest way to get the last number inserted into the LinkedHashSet<Integer>
please?
将最后一个数字插入LinkedHashSet<Integer>
请的最简单方法是什么?
采纳答案by Juvanis
First of all, I agree with corsiKa's solution which suggests an extended version of LinkedHashSet
class that contains a pointer to the last element. However, you can use a traditional way by consuming some space for an array:
首先,我同意 corsiKa 的解决方案,它建议LinkedHashSet
包含指向最后一个元素的指针的类的扩展版本。但是,您可以通过为数组消耗一些空间来使用传统方式:
set.toArray()[ set.size()-1 ] // returns the last element.
回答by corsiKa
There's no prebaked option for this. There's two off-the-cuff options, and neither are good:
对此没有预烘焙选项。有两种现成的选择,但都不是很好:
The Order n approach:
n 阶方法:
public <E> E getLast(Collection<E> c) {
E last = null;
for(E e : c) last = e;
return last;
}
Yuck! But there's also an Order 1 approach:
糟糕!但也有一个 Order 1 方法:
class CachedLinkedHashSet<E> extends LinkedHashSet {
private E last = null;
public boolean add(E e) {
last = e;
return super.add(e);
}
public E getLast() {
return last;
}
}
This is off the cuff, so there might be a subtle bug in it, and for sure this isn't thread safe or anything. Your needs may vary and lead you to one approach over another.
这是现成的,所以它可能有一个微妙的错误,而且肯定这不是线程安全的或任何东西。您的需求可能会有所不同,并导致您采用一种方法而不是另一种方法。
回答by Alexis C.
回答by user2179737
here is a implementation that adds method to access the last entry O(1):
这是一个添加方法来访问最后一个条目 O(1) 的实现:
enjoy...
请享用...
回答by Renjith
Sets are independent of order.We cannot access element by index.If you require last element,
集合与顺序无关。我们不能通过索引访问元素。如果您需要最后一个元素,
1)create new ArrayList(Set)
1) 创建新的 ArrayList(Set)
The last element of an arrayList can be accessed easily
可以轻松访问 arrayList 的最后一个元素