package collection;
public interface MyMap<K,V> {
public void put(K key,V value);
public V get(K key);
public boolean containsKey(K key);
public boolean containsValue(V value);
public void remove(K key);
public int size();
public boolean isEmpty();
}
package collection;
public class MyHashMap<K,V> implements MyMap<K,V> {
private static final int INITIAL_CAPACITY = 16;
private int size;
private Entry[] table;
public MyHashMap() {
table = new Entry[INITIAL_CAPACITY];
}
public static void main(String[] args) {
MyMap<String,String> map = new MyHashMap<>();
System.out.println(map);
map.put("a","AA");
map.put("b","BB");
map.put("c","CC");
map.put("d","DD");
map.put("a","dudu");
String str = map.get("e");
System.out.println(str);
System.out.println(map.toString());
map.remove("d");
Boolean b = map.containsKey("bb");
System.out.println(b);
}
@Override
public void put(K key, V value) {
int index = hash(key);
Entry entry = new Entry(key,value,index,null);
if (table[index]==null){
table[index] = entry;
}else{
Entry e =table[index];
Entry last = e;
while (e!=null){
if (e.key.equals(key)){
e.value = value;//如果key相同,则直接替换value的值
return;
}
last = e;
e = e.next;//循环下一个
}
//上面整个循环结束,没有return,则说明整个单向列表中没有Entry的key和传入的key相等
//则添加到链表的最后
last.next = entry;
}
size++;
}
private int hash(Object key){
int hashcode = key.hashCode();//返回的是int,有可能是负数
hashcode=hashcode<0?(-hashcode):hashcode;//hashcode必须是正数
return hashcode&(table.length-1);//位运算,效率更高,返回的是[0,table.length-1]范围的一个数字
};
@Override
public V get(K key) {
int index = hash(key);
if (table[index]!=null){
Entry e = table[index];
while (e!=null){
if (e.key.equals(key)){
return (V) e.value;
}
e = e.next;
}
}
return null;
}
@Override
public String toString() {
// [{a:AA,b:bb},{a:CC,c:DD}]
StringBuilder sb = new StringBuilder();
sb.append("[");
for (Entry e:table) {
while (e != null) {
sb.append("{" + e.key + ":" + e.value + "},");
e = e.next;
}
}
sb.append("]");
return sb.toString();
}
@Override
public boolean containsKey(K key) {
int index = hash(key);
if (table[index]!=null){
Entry e = table[index];
while (e!=null){
if (e.key.equals(key)){
return true;
}
e = e.next;
}
}
return false;
}
@Override
public boolean containsValue(V value) {
return false;
}
@Override
public void remove(K key) {
int index = hash(key);
if (table[index]!=null){
Entry e = table[index];
Entry previous = null;//上一个节点,如果没有则为null
while(e!=null){
if(e.key.equals(key)){
// 说明是第0个节点
if(previous==null){
table[index]=e.next;//直接把下一个节点前移
}else{
previous.next = e.next;//相当于把当前节点跳过(在链表中移除)
}
size--;
}
previous = e;
e = e.next;
}
}
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size==0;
}
}
class Entry<K,V> {
K key;
V value;
int hash;
Entry next;//下一个节点
public Entry(K key, V value, int hash, Entry next) {
this.key = key;
this.value = value;
this.hash = hash;
this.next = next;
}
public Entry() {};
}