I implemented a CustomHashMap
in Java, and would like to know if my approach is good or not.
Below I am sharing the complete code of my CustomHashMap
:
CustomHashMap.java
import java.util.Iterator;
import java.util.Objects;
import com.custom.utils.*;
public class CustomHashMap<K, T> implements Iterable<Entity> {
private static final int capacity_init = 10;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
private int indexCount = 0;
Entity[] bucket = null;
Entity[] bucketItr = null;
public CustomHashMap() {
init(capacity_init);
}
public CustomHashMap(int capacity) {
init(capacity);
}
private void init(int intcapacity) {
bucket = new Entity[intcapacity];
}
private int hash(Object key) {
return key.hashCode() >> 1;
}
public void add(K key, T value) {
int hashcode = hash(key);
if(indexCount == bucket.length){
Entity[] obj = bucket;
int k = (int) (obj.length*2);
bucket = new Entity[k];
System.arraycopy(obj, 0, bucket, 0, indexCount-1);
}
if (bucket[hashcode] == null) {
indexCount++;
Entity head = new Entity(key, value, null);
bucket[hashcode] = head;
} else {
Entity temp = bucket[hashcode];
while (temp.next != null) {
temp = temp.next;
}
Entity neEntity = new Entity(key, value, null);
neEntity.next = temp;
bucket[hashcode] = neEntity;
}
bucketItr = new Entity[bucket.length];
System.arraycopy(bucket, 0, bucketItr, 0, bucket.length);
}
public T get(K key) {
int hashcode = hash(key);
if (bucket[hashcode] == null) {
return null;
} else {
Entity temp = bucket[hashcode];
while (temp != null) {
if (temp.key.equals(key)) {
return (T) temp.value;
}
temp = temp.next;
}
return null;
}
}
public void delete(K key) {
int hashcode = hash(key);
Entity deleteNode = bucket[hashcode];
deleteNode = null;
bucket[hashcode] = deleteNode;
}
@Override
public Iterator<Entity> iterator() {
// TODO Auto-generated method stub
bucketItr = new Entity[indexCount];
int entryCount = 0;
for (Entity e : bucket) {
if (Objects.nonNull(e)) {
bucketItr[entryCount] = e;
entryCount++;
}
}
return new MapItr();
}
class MapItr implements Iterator<Entity> {
int count = 0;
Entity node = bucketItr[0];
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return count < bucketItr.length;
}
@Override
public Entity next() {
Entity result = null;
if (hasNext()) {
result = node;
if ( Objects.nonNull(node) && node.next != null) {
node = node.next;
} else {
count++;
if (count < bucketItr.length)
node = bucketItr[count];
}
return result;
} else {
return null;
}
}
}
}
Entity.java
public class Entity<K, T> {
public K key;
public T value;
public Entity next;
public Entity(K key, T value, Entity next) {
this.key = key;
this.value = value;
this.next = next;
}
}
Please suggest improvements and things which you feel I need to add to it.