Created
November 18, 2020 04:55
-
-
Save shahzadaazam/bc287ca0f9bebe4418911d8308343bc0 to your computer and use it in GitHub Desktop.
Custom implementation of HashTable using LinkedLists and Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
class Main { | |
public static void main(String[] args) { | |
HashTable<String, String> hashTable = new HashTable<>(); | |
hashTable.put("Azam", "hello"); | |
hashTable.put("Shahani", "world"); | |
System.out.println(hashTable.get("Azam")); | |
} | |
} | |
class HashTable<K, V> { | |
private static final int HASH_TABLE_SIZE = 10; | |
private final LinkedList<KeyValuePair<K, V>>[] tableArr; | |
public HashTable(){ | |
tableArr = new LinkedList[HASH_TABLE_SIZE]; | |
for(int i = 0; i < tableArr.length; i++) { | |
tableArr[i] = new LinkedList<>(); | |
} | |
} | |
public void put(K key, V value) { | |
int index = computeHashCode(key) % tableArr.length; | |
LinkedList<KeyValuePair<K, V>> linkedList = tableArr[index]; | |
KeyValuePair<K, V> keyValuePair = new KeyValuePair<>(key, value); | |
linkedList.add(keyValuePair); | |
} | |
public V get(K key) { | |
int index = computeHashCode(key) % tableArr.length; | |
LinkedList<KeyValuePair<K, V>> linkedList = tableArr[index]; | |
V value = null; | |
for (KeyValuePair<K, V> item : linkedList) { | |
if (item.getKey().equals(key)) { | |
value = item.getValue(); | |
} | |
} | |
return value; | |
} | |
private int computeHashCode(K key) { | |
return key.hashCode(); | |
} | |
} | |
class KeyValuePair<K, V> { | |
private K key; | |
private V value; | |
public KeyValuePair(K key, V value) { | |
this.key = key; | |
this.value = value; | |
} | |
public K getKey() { | |
return key; | |
} | |
public void setKey(K key) { | |
this.key = key; | |
} | |
public V getValue() { | |
return value; | |
} | |
public void setValue(V value) { | |
this.value = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment