Pr0pagate
Pr0pagate

Reputation: 199

Does HashSet Provide Any Added Value to Performance in This Instance?

So, I'm working with an existing method in Java that returns a List (ArrayList). However, I want to add some functionality to it so that if specified, it will exclude a certain Object. Now I understand that in general using contains() on a HashSet yields better performance vs an ArrayList, but I'm wondering if there is a justifiable performance boost to be had in the two variations of the code I have below:

Notes: listOfAccounts is an ArrayList returned from a DAO call. personalAccount is an Object of type Account.

if (excludePersonalAccount) {
   Set<Account> accounts = new HashSet<Account>(listOfAccounts);
   if (accounts.contains(personalAccount) {
      listOfAccounts.remove(personalAccount);
   }
}

VS

if (excludePersonalAccount) {
   listOfAccounts.remove(personalAccount)
}

Upvotes: 1

Views: 45

Answers (1)

Jacob G.
Jacob G.

Reputation: 29730

Set<Account> accounts = new HashSet<Account>(listOfAccounts);

The above line takes all of the elements of the ArrayList and adds it to the HashSet. Instead of doing all of that, you could iterate over the List and look to see if your element is contained inside it. If it is, then you can remove it (which is essentially what you second snippet is doing).

For that reason, the second snippet is preferred, as they both run in linear time.

Upvotes: 2

Related Questions