hashtable - Java Hash Table Search Function -
i have hash table created seem stuck on 1 problem. have data in hash table , when searching data returns expected. however, if search not in table still hashes out element present, not return false.
for example: have hello key in hash table, lets element 15. search world , hashes same hello, example.
what expect code return null because though key's hashed same, not equal. code below, return key/data (record) hello instead.
@suppresswarnings("rawtypes") public record search(t k) { int = hash(k);//assign computed hash value (combination of record class hashcode , table's hash function above) i. if (a[i] == null || a[i].record.equals(k)) { return null; } else if (!a[i].record.equals(i) && a[i].record.getkey() != k) {//otherwise, record found , if key stored not equal key being searched return null return a[i].record; } else { //otherwise record not first record in linked list cursor = a[i]; //set cursor equal entire list of records sorted hash key reference if (cursor.record.getkey() != k) { //if key @ cursor.record not equal key (k), move onto cursor.next return cursor.next.record; } } return null; }
record class
public class record<t, u> { private t key;//contacts name, , value hashed. inserted, searched , deleted private u data;//this data contacts address, when key hashed, nothing done value except //either stored or retrieved hash table when key used public t getkey() { return key;//returns value stored key } public void setkey(t k) { this.key = k;//used during insert operation set key's value. } public u getdata(t k) {//retrieve data stored associated key has been updated, searhed or being written file return data; } public void setdata(u data) {//adds data records data element this.data = data; } public int hashcode(t k) {//when hash code function called, returns mathematical representation of key, passed //it returns absolute value of generic hashcode() function. further computations required in table class, since hash created here //can large , throw , exception. example, hash "chris" after computation has been performed 94639767, //much larger our array. cause indexoutofboundsexception(). return math.abs(k.hashcode()); } public boolean equals(record<t, u> r) { //this equals method, doesn't override generic equals() method provided java. instead, method created use instead of generic //equals method. when called, has value computed above, additional math table class, compared of elements //in array. if match found, returns true return key.equals(r.key); } }
this classic == vs .equals() problem.
a[i].record.getkey() != k
can true while a[i].record.getkey().equals(k)
true.
you should use (!a[i].record.getkey().equals(k))
instead of a[i].record.getkey() != k
Comments
Post a Comment