• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method to count no of elements or objects landing in same bucket in Java HashSet  RSS feed

 
priyankjecrc jain
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any way to find how many number of elements are landing in same bucket in HashSet. I know Reflection could be one way but i am not able to design a program for that.
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you need this information?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Although the JavaDoc does mention the concept of buckets, and that it is related to capacity, it is not documented on how to obtain the capacity. Furthermore, there is no documentation on how to map an object hash code to a bucket. Besides it being a complex formula, it is an implementation detail, and can vary with each version of Java.

Henry
 
priyankjecrc jain
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Henry thanks for concern. Is there any way by which i can keep count of number of objects or elements producing same HashCode. I am not able to design logic for that.
 
priyankjecrc jain
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Paweł Baczyński I confronted a situation while coding in which objects based on some logic are producing same hashcode and falling into same bucket . My job is to design a logic that can keep count of all those objects who are having same hash code.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
priyankjecrc jain wrote:Is there any way by which i can keep count of number of objects or elements producing same HashCode. I am not able to design logic for that.


Well, if you want a design that will track it on the fly, one option would be to create a wrapper set. This is how the Collections class does it with the synchronizedSet() method. This wrapper can then track the count as elements are added and removed from the set. Of course, you will need to use this wrapper set instead, which require code changes.

Another option is to do the count as you need it (and not on the fly) -- which can be done by simply iterating and checking.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!