java - Fetch the most recent inserted element in LinkedHashSet efficiently -


this question has answer here:

according linkedhashset's javadoc, keep insertion order of inserted elements using doubly linked list internally.

it maintains doubly-linked list running through of entries. linked list defines iteration ordering, order in elements inserted set (insertion-order)

if want fetch first inserted element, can use code like:

linkedhashset.iterator().next() 

this give me first inserted element in set in o(1).

i trying solve problem, requires me access recent inserted element set in o(1), , let's assume there not duplicated element inserted set. example,

linkedhashset.add(2); // recent inserted element in set 2 linkedhashset.add(3); // recent inserted element in set 3 linkedhashset.add(5); // recent inserted element in set 5 linkedhashset.remove(5); // recent inserted element in set 3 because 5 removed , not in set 

since doubly linked list in set, seems recent element should last 1 in doubly linked list , should able accessed in o(1) if there api it.

my question is: there way in jdk or need create own reversediteratinglinkedhashset this?

basically, try find set data structure o(1) time complexity operations including: insertion/deletion/search/check recent inserted element in set. built in linkedhashset seems fit small modification internally not sure if can done default jdk class api or not.

note: checked jdk's source code , know linkedhashset internally implemented linkedhashmap, , if there solution use linkedhashmap access recent inserted element in o(1), useful me too.

thanks lot.

unfortunately, seems there's no direct/clean way access added element in linkedhashset (or linkedhashmap) in o(1).

a clean way convert set array , access last element, o(n).

a dirty way use reflection access internal hash map, map's head entry , entry's predecessor (before).


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -