java - Testing containment with HashSet -
i writing programme in java utilize hashset (and hashmap). having problem getting contains (and containskey) method(s) work. guess have override equals method somewhere work. thought next piece of code produce output: true. thoughts on how can 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 utilize stringbuilder
here, since stringbuilder
uses reference equality, not equality of contents. utilize string
instead.
(this makes sense, stringbuilder
mutable, , 2 stringbuilder
s may equal @ 1 point , unequal later. it's not question of writing hashcode()
or equals
method, since stringbuilder
isn't class wrote, it's built java.)
java hashset
No comments:
Post a Comment