I have a class with 3 attributes. One of the attributes is used as a unique key , so I use that one key in my equals and hashcode method.
Now once the set is built, during lookup, I have only the primary key (unique key) and I will have to construct a dummy object with unique key and setting other two values to 0 (default values) and then I say
Chapter myObject = new Chapter(uniqueKey,0,0);
hashSet.contains(myObject); // This will work.
Is this a correct usage for Hashset lookup? Is there any other better way because I am not a fan of setting bogus values on a object.
One way to make this less verbose is to define a
Chapter()constructor that takes auniqueKeyargument and fills in the rest, and then use:Since you are throwing away the object anyways.
However, since you have a
uniqueKey, which I assume is unique to each instance of aChapter, have you considered using aHashMapinstead? Then you could just useuniqueKeyas keys, and you’d just have to check whether the key is present (eg: usingHashMap.containsKey()) or not:With a HashMap, you can also just get the Object you want with
.get():This will give you the
Chapterobject if the supplieduniqueKeymaps to an object, ornullif doesn’t.