Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last of LinkedHashSet

Tags:

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?

like image 606
James Raitsev Avatar asked Dec 24 '12 17:12

James Raitsev


People also ask

Does LinkedHashSet maintain order?

Yes, the order is preserved in case the incoming collection is ordered.

Are duplicates allowed in LinkedHashSet?

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).


1 Answers

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.

like image 168
corsiKa Avatar answered Sep 22 '22 12:09

corsiKa