Questions
Hi I m wondering if it is possible to access the contents of a HashSet directly if you have the Hashcode for the object you re looking for, sort of like using the HashCode as a key in a HashMap.
I imagine it might work something sort of like this:
MyObject object1 = new MyObject(1);
Set<MyObject> MyHashSet = new HashSet<MyObject>();
MyHashSet.add(object1)
int hash = object1.getHashCode
MyObject object2 = MyHashSet[hash]???
Thanks!
edit: Thanks for the answers. Okay I understand that I might be pushing the contract of HashSet a bit, but for this particular project equality is solely determined by the hashcode and I know for sure that there will be only one object per hashcode/hashbucket. The reason I was pretty reluctant to use a HashMap is because I would need to convert the primitive ints I m mapping with to Integer objects as a HashMap only takes in objects as keys, and I m also worried that this might affect performance. Is there anything else I could do to implement something similar with?
Answers
The common implementation of HashSet is backed (rather lazily) by a HashMap so your effort to avoid HashMap is probably defeated.
On the basis that premature optimization is the root of all evil, I suggest you use a HashMap initially and if the boxing/unboxing overhead of int to and from Integer really is a problem you ll have to implement (or find) a handcrafted HashSet using primitive ints for comparison.
The standard Java library really doesn t want to concern itself with boxing/unboxing costs.
The whole language sold that performance issue for a considerable gain in simplicity long ago.
Notice that these days (since 2004!) the language automatically boxes and unboxes which reveals a "you don t need to be worrying about this" policy. In most cases it s right.
I don t know how richly featured your HashKeyedSet needs to be but a basic hash-table is really not too hard.
Source
License : cc by-sa 3.0
http://stackoverflow.com/questions/26986587/accessing-a-hashset-using-the-hashcode-directly-java
Related