stasis
stasis

Reputation: 11

HashSet<String> .contains()

I'm having issues using .contains to check if a String is stored in a HashSet.

import java.util.HashSet;

public class Controller
{
    private Queue<String> queue;
    private HashSet<String> blocked;

    public Controller()
    {
        queue = new Queue<String>();
        blocked = new HashSet<String>();
    }

    public void add(String item)
    {        
        if (!(blocked.contains(item))) queue.add(item);
    }
}

I've had a look around and understand that I need to override the .equals method. Does this mean that I'd have to make a new class that extends HashSet and then declare an instance of that new class in place of 'HashSet blocked;'?

I'm aware of the reason that simply using == to compare two Strings doesn't work, but I'm confused because the code below does seem to work in some cases but not all.

Any advice would be much appreciated!

Regards

Upvotes: 0

Views: 6885

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

You do not need to override the equals method - the String already has a very good pair of hashCode/equals that are efficient in terms of CPU cycles and in terms of distributing different strings to different hash buckets.

A pair of hashCode/equals methods is required for items placed in a hash set in order to enable the correct work of the container: hashCode decides on the hash "bucket" in which the object is placed, and equals resolves collisions among non-equal objects with identical hash codes.

Wikipedia has an illustrated article on hash tables. Read through it to improve your understanding of the hashCode/equals concepts, they are fundamental to using unsorted associative containers in any language, including Java.

Upvotes: 2

Related Questions