I want to make a method to count how many comparisons are made when i want to put a new random key in my hash map . The code I used to put new keys in the map is the following :
public void put(int key, int value) {
int hash = (key % table.length);
int initialHash = -1;
int indexOfDeletedEntry = -1;
while (hash != initialHash
&& (table[hash] == DeletedEntry.getUniqueDeletedEntry()
|| table[hash] != null
&& table[hash].getKey() != key)) {
if (initialHash == -1)
initialHash = hash;
if (table[hash] == DeletedEntry.getUniqueDeletedEntry())
indexOfDeletedEntry = hash;
hash = (hash + 1) % table.length;
}
if ((table[hash] == null || hash == initialHash)
&& indexOfDeletedEntry != -1) {
table[indexOfDeletedEntry] = new HashEntry(key, value);
size++;
} else if (initialHash != hash)
if (table[hash] != DeletedEntry.getUniqueDeletedEntry()
&& table[hash] != null && table[hash].getKey() == key)
table[hash].setValue(value);
else {
table[hash] = new HashEntry(key, value);
size++;
}
if (size >= maxSize)
resize();
}
The class for the deleted entry is the following :
public class DeletedEntry extends HashEntry {
private static DeletedEntry entry = null;
private DeletedEntry() {
super(-1, -1);
}
public static DeletedEntry getUniqueDeletedEntry() {
if (entry == null)
entry = new DeletedEntry();
return entry;
}
}
Also , HashEntry class has 2 int variables , int key and int value . Any Idea how i can count the comparisons ? This is what I've done in my main:
Random rand = new Random();
int[] comparisons = new int[20];
int key = 0;
for (int k=0;k<20;k++){
key = rand.nextInt(1000) + 1;
}
(I'm assuming that this is a learning exercise of some kind. Hence advice to use or extend an existing Map implementation is irrelevant.)
The simple answer is that you increment a counter each time you "compare" keys. You could do that inline, or you could write yourself a little helper method like this:
private boolean compareKeys(int key1, int key2) {
count++;
return key1 == key2;
}
and then change your code to use this helper each time it compares keys; e.g.
while (hash != initialHash
&& (table[hash] == DeletedEntry.getUniqueDeletedEntry()
|| table[hash] != null
&& !compareKeys(table[hash].getKey(), key))) {
and
if (table[hash] != DeletedEntry.getUniqueDeletedEntry()
&& table[hash] != null
&& compareKeys(table[hash].getKey(), key))
There really is no clever solution to this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With