java - Weird HashTable ArrayIndexOutOfBounds Exception -


the test testgetbucket() not working when key greater 5 characters. example if of puppy names longer 5 characters, test return arrayindexoutofbounds exception getbucket method.

@test     public void testgetbucket() {         list<puppy> puppies = getpuppies();         myhashtable<string, puppy> instance = new myhashtable<>(defaultcapacity, defaultloadfactor);          (int = 0; < 10; i++) {             puppy puppy = puppies.get(i);             instance.put(puppy.name, puppy);             system.out.print(i);         }          list<keyvaluepair<string, puppy>> actual = instance.getbucket(8);         assertequals("size of bucket three", 3, actual.size());         (int = 0; < actual.size(); i++) {             keyvaluepair<string, puppy> p = actual.get(i);             if (p.key.equals("bob")) {                 assertequals("bucket contains " + p.value.name, puppies.get(1), p.value);             } else if (p.key.equals("francois")) {                 assertequals("bucket contains " + p.value.name, puppies.get(5), p.value);             } else if (p.key.equals("inigo")) {                 assertequals("bucket contains " + p.value.name, puppies.get(8), p.value);             }         }          actual = instance.getbucket(3);         assertequals("size of bucket zero", 0, actual.size());          actual = instance.getbucket(0);         assertequals("size of bucket 1", 1, actual.size());         keyvaluepair<string, puppy> p = actual.get(0);         assertequals("bucket contains " + p.value.name, puppies.get(2), p.value);     }    public void put(k key, v value)     {        remove(key);        keyvaluepair<k,v> element = new keyvaluepair<k,v>(key, value);        getbucket(getbucketindex(key.hashcode())).add(element);     }   public int getbucketindex(int hashcode)     {         return hashcode % getnumberofcollisionbuckets();     }  public list<keyvaluepair<k,v>> getbucket(int bucketindex)     {          return collisionbuckets[bucketindex];     } 

i'm gonna go on limb here , problem part

return hashcode % getnumberofcollisionbuckets(); 

if naming guidance problem hashcode. have no idea why decide go such fragile implementation.

when error occurring hashcode must of value give result higher array's index value after modulation.

so way fix this? stop relying on hashcode getting array index... that's not it's purpose.


Comments