Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Code.Hashing;
- public class ClosedHashTable<K, V> {
- final int hashSize = 23;
- private Entry<K, V>[] values;
- ClosedHashTable() {
- values = new Entry[hashSize];
- }
- private int hashFunction(K key) {
- return Math.abs(key.hashCode()) % hashSize;
- }
- // Metode untuk menyelesaikan tabrakan (collision) dengan linear probing
- private int resolveCollision(K key, int index) {
- int initialIndex = index;
- while (values[index] != null) {
- if (values[index].key.equals(key))
- return index;
- index = (index + 1) % hashSize; // Linear probing
- if (index == initialIndex)
- return -1;
- }
- return index;
- }
- // Metode untuk mendapatkan indeks berdasarkan kunci menggunakan resolveCollision
- private int getIndex(K key) {
- return resolveCollision(key, hashFunction(key));
- }
- // Metode untuk mencari indeks dengan kunci yang sesuai menggunakan linear probing
- private int collidedIndex(K key) {
- int initialIndex = hashFunction(key);
- int index = initialIndex;
- Entry<K, V> result = values[index];
- if (result != null)
- if (result.key.equals(key))
- return index;
- do {
- do {
- index = (index + 1) % hashSize;
- if (index == initialIndex)
- return -1;
- } while (values[index] == null);
- result = values[index];
- } while (!result.key.equals(key));
- return index;
- }
- // Metode untuk menambahkan elemen baru ke tabel hash
- boolean put(K key, V value) {
- int index = getIndex(key);
- if (index == -1)
- return false;
- values[index] = new Entry<K, V>(key, value);
- return true;
- }
- // Metode untuk mendapatkan nilai (value) berdasarkan kunci (key)
- V get(K key) {
- int index = collidedIndex(key);
- return index == -1 ? null : values[index].value;
- }
- // Metode untuk mencetak isi tabel hash
- void print() {
- for (Entry<K, V> entry : values) {
- if (entry != null)
- System.out.println(entry.toString());
- }
- }
- }
- class Entry<K, V> {
- K key;
- V value;
- public Entry(K key, V value) {
- this.key = key;
- this.value = value;
- }
- @Override
- public String toString() {
- return "{" + key.toString() + ":" + value.toString() + "}";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment