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
StringBuilderhere, sinceStringBuilderuses reference equality, not equality of contents. Just useStringinstead.(This makes sense, as
StringBuilderis mutable, and twoStringBuilders may be equal at one point and unequal later. It’s not a question of writing ahashCode()orequalsmethod, sinceStringBuilderisn’t a class you wrote, it’s built into Java.)