Skip to content

Instantly share code, notes, and snippets.

@dcbriccetti
Created March 23, 2021 23:21
Show Gist options
  • Save dcbriccetti/de9d1e7c0acf67e2f326ce86c129fcac to your computer and use it in GitHub Desktop.
Save dcbriccetti/de9d1e7c0acf67e2f326ce86c129fcac to your computer and use it in GitHub Desktop.
package examples.maps;
import java.util.Arrays;
import java.util.stream.IntStream;
public class HashMap<K, V> {
public static class Bucket<K, V> {
public static class KeyAndValue<K, V> {
public K key;
public V value;
public KeyAndValue(K key, V value) {
this.key = key;
this.value = value;
}
@Override public String toString() {
return key + ": " + value;
}
}
public KeyAndValue<K, V> keyAndValue;
public Bucket<K, V> nextBucket;
public Bucket(K key, V value) {
keyAndValue = new KeyAndValue<>(key, value);
}
@Override public String toString() {
return "{" + keyAndValue + ", nextBucket=" + nextBucket + "}";
}
}
private final int NUM_BUCKETS = 16;
public Bucket<K, V>[] buckets = new Bucket<K, V>[NUM_BUCKETS];
public void put(K key, V value) {
int index = hashIndex(key);
if (this.buckets[index] == null) {
this.buckets[index] = new Bucket<>(key, value);
}
}
private int hashIndex(K key) {
IntStream codePoints = key.toString().codePoints();
var buffer = new StringBuffer();
codePoints.forEach(point -> buffer.append(String.format("%d ", point)));
int sum = key.toString().codePoints().sum();
int index = sum % NUM_BUCKETS;
System.out.printf("%s %s %d %d\n", key, buffer, sum, index);
return index;
}
public static void main(String[] args) {
var m = new HashMap<String, Integer>();
m.put("Dave", 100);
m.put("Ben", 200);
m.put("Bne", 200);
System.out.println(Arrays.toString(m.buckets));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment