I'd like to store a list of numbers 1,2,3,4 - (lets start with List<Integer>
)
I'd like to make sure numbers are unique (ok, fine, Set<Integer>
)
I'd like to guarantee order (ok ... 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?
Yes, the order is preserved in case the incoming collection is ordered.
Duplicate values are not allowed in LinkedHashSet. One NULL element is allowed in LinkedHashSet. It is an ordered collection which is the order in which elements were inserted into the set (insertion-order).
There's no prebaked option for this. There's two off-the-cuff options, and neither are good:
The Order n approach:
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:
class CachedLinkedHashSet<E> extends LinkedHashSet<E> { private E last = null; @Override 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With