Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Entry<K, V> {
- K key;
- V value;
- Entry<K, V> next;
- public Entry(K key, V value, Entry<K, V> next) {
- this.key = key;
- this.value = value;
- this.next = next;
- }
- /**Usually in HashMap Entry Looks like this
- *
- * ------------------------------------------
- * | Key | Value | Next Entry reference |
- * ------------------------------------------
- * **/
- 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;
- }
- public Entry<K, V> getNext() {
- return next;
- }
- public void setNext(Entry<K, V> next) {
- this.next = next;
- }
- }
- /**HashMap**/
- public class CustomHashMap<K, V> {
- private Entry<K, V>[] buckets;
- private static final int capacity = 16;
- public CustomHashMap(Entry<K, V>[] buckets) {
- this.buckets = new Entry[capacity];
- }
- public void put(K key, V value) {
- //check if key is null because it does not allow to store null.
- if (key == null) {
- return;
- }
- //get the bucket count for key using hash function
- int bucketCount = hash(key);
- //create new Entry
- Entry<K, V> newEntry = new Entry<K, V>(key, value, null);
- //check in same bucket whether already we have entry or not
- //if no entry present then directly add this entry
- if (buckets[bucketCount] == null) {
- buckets[bucketCount] = newEntry;
- } else {
- Entry<K, V> previous = null;
- Entry<K, V> current = buckets[bucketCount];
- while (current != null) {
- //if key is same then replace the value
- if (current.getKey().equals(key)) {
- current.setValue(value);
- break;
- }
- previous = current;
- current = current.getNext();
- }
- if (previous != null)
- previous.setNext(newEntry);
- }
- }
- public V get(K key) {
- int hash = hash(key);
- Entry<K, V> entry = buckets[hash];
- if (entry.getKey().equals(key)) {
- return entry.getValue();
- } else {
- return null;
- }
- }
- private int hash(K key) {
- return key.hashCode() % capacity;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement