Access HashSet directly using hashcode? (JAVA)

Hi, I want to know if you can directly access the content of the HashSet if you have the hashcode of the object you are looking for, which is a bit like using the hashcode as the key in the HashMap

I think it might look like this:

MyObject object1 = new MyObject(1); 

Set<MyObject> MyHashSet = new HashSet<MyObject>();

MyHashSet.add(object1)

int hash = object1.getHashCode

MyObject object2 = MyHashSet[hash]???

thank you!

Editor: Thank you for your answer OK, I understand that I may promote the HashSet contract, but for this specific project, the equality is completely determined by the hash code. I'm sure there is only one object for each hash code / hashbucket The reason why I am very reluctant to use HashMap is that I need to convert the original int i am mapping to an integer object. Because HashMap only accepts objects as keys, I am also worried that this may affect performance What else can I do to achieve something like this?

Solution

The common implementation of HashSet is supported by HashMap (quite lazy), so you may fail to avoid using HashMap

On the basis that premature optimization is the root of all evil, I suggest you initially use HashMap. If int and boxing / unpacking overhead from integer are actually a problem, you must implement (or find) a handmade HashSet and compare it with the original integer The standard Java library really doesn't want to focus on packing / unpacking costs Long ago, the whole language sold this performance problem very simply Please note that these days (since 2004!) Language automatic box packing and unpacking, showing "you don't need to worry about this" policy In most cases, this is true

I don't know how rich your hashkeyedset needs to be, but the basic hash table is really not too difficult

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>