0

I have a scenario where I have to fetch all the elements in the bucket of a HashMap / Set by using generated hashcode. For example,

public class Interval{
    private int minimum;
    private int maximum;

    Interval(int minimum, int maximum){
    this.minimum = minimum;
    this.maximum = maximum;
    }
    //getters &setters

     @Override
    public int hashCode() {
         //for now say I return hash as below
        return (minimum % 500)  
    }
}

Set <Interval> intervals = new <>Set();
intervals.add(new Interval(10,100));
intervals.add(new Interval(20,300));
intervals.add(new Interval(50,100));
intervals.add(new Interval(501,1000));

I will generate same hashcode for a interval falling between 500 intervals i.e. any interval between 1-500 will generate same hashcode and hence will be put in same bucket. Hence, for above, the internal data strcture could look like

|wsed@wed:|Object(10,100),Object(20,300),Object(10,100)|,wesd@3eww:|Object(10,200)||

Suppose here | | block is representing a Set & value inside it are hashcode : Linked List

I know I could do manual implementations of the data structure mentioned but is there any way in java of doing that.

Edit: Why I need it: I need to fetch all elements of same bucket and do merging of intervals to optimise the intervals falling in a range. Hence, I need collision to happen.

Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86
  • 1
    Your posted code isn't compilable. You should write your hash code to minimize the likelihood of collision, not encourage it. `HashMap` scrambles the hash code of its keys anyway, so you can't game it in the way you describe, and you shouldn't regardless. – Lew Bloch Mar 03 '17 at 19:07
  • @jarrod I don;t see it as duplicate of the question http://stackoverflow.com/questions/5830575/multimap-vs-multivalue-map – Vinay Prajapati Mar 03 '17 at 19:11
  • 1
    It seems that the degree of control/customization you need calls for a custom structure. – bichito Mar 03 '17 at 19:18
  • @LewBloch I have edited my answer. – Vinay Prajapati Mar 03 '17 at 19:34

0 Answers0