简体   繁体   中英

Testing containment with HashSet

I am writing a program in Java where I would like to use HashSet (and HashMap). I am having trouble getting the contains (and containsKey) method(s) to work. I guess I have to override some equals method somewhere for this to work. The idea is to get the following piece of code to produce output: true. Any thoughts on how I can do that?

import java.util.HashSet;
import java.util.Set;

public class Sets {

    public static void main(String args[]){

        Set<StringBuilder> wordSet = new HashSet<StringBuilder>();
        StringBuilder element = new StringBuilder("Element");
        wordSet.add(element);
        StringBuilder element2 = new StringBuilder("Element");
        System.out.println(wordSet.contains(element2));

    }

}

You can't use StringBuilder here, since StringBuilder uses reference equality, not equality of contents. Just use String instead.

(This makes sense, as StringBuilder is mutable, and two StringBuilder s may be equal at one point and unequal later. It's not a question of writing a hashCode() or equals method, since StringBuilder isn't a class you wrote, it's built into Java.)

StringBuilder does not override the default hashCode() and equals() methods, so it uses Object's implementation - which basically does a == check. as youre not using the exact same StringBuilder instance, the contains() call returns false.

as the class is final you cannot extend it to add equals() and hashCode(), so you need to you your own class instead.

Don't use a StringBuilder. Use a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM