Is it worth checking LinkedHashSet.contains (...) before adding?

I am using LinkedHashSet to implement a record-ordered collection. If a duplicate item is added, it must come at the end, and the entry already in the set must be removed.

I am debating whether it is worth checking set.contains (entry) before I call set.remove (entry)? Essentially the check contains () every time you suggest any time / space for just blindly calling remove () every time?

Set<Integer> set = new LinkedHashSet<>();
// The below
set.remove(entry);
set.add(entry);
// Versus the below
if (set.contains(entry)) {
set.remove(entry);
}
set.add(entry);

      

+3


source to share


2 answers


I would recommend against calling both contain and delete. Both calls must search chains to find an element, and contains

it does so no faster than remove

. This way, you potentially double your required call time each time.

You can view the code for contains

and remove

yourself.



You will find that both options are possibly iterating through the hash chains at some point ( remove

in the HashMap removeNode

and contains

in the HashMap getNode

), which can be fortunate if your set is under heavy load.

Unless your set is under heavy load, then it's probably not worth it anyway, but not a big deal, since in sparse hash chains the expected search / delete is O (1) (i.e. will be just as fast , whether you have 5 items or 5000).

+1


source


LinkedHashSet

uses HashMap

behind the scenes remove(Object)

deletes Object

only if it is an contains

Object, therefore not needed, and increases the time complexity in case the object exists in the set.



+1


source







All Articles