package com.bjsxt.task;
/**
* <p>Title: Node</p>
* <p>Description: 自定义节点</p>
* @author xiaoding
* @date Jun 2, 2020
* @version 1.0
*/
public class Node<K,V> {
K key; //键
V value; //值
int hash; //hashCode值
Node<K,V> next; //节点
//无参构造方法
public Node() {}
//有参构造方法
public Node(K key,V value,int hash,Node<K,V> next) {
this.key = key;
this.value = value;
this.hash = hash;
this.next = next;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public String toString() {
return key + "=" + value + "," + next;
}
}
package com.bjsxt.task;
import java.util.Arrays;
import java.util.HashMap;
/**
* <p>Title: MyHashMap</p>
* <p>Description: 自定义HashMap类</p>
* @author xiaoding
* @date Jun 2, 2020
* @version 1.0
*/
public class MyHashMap<K,V> {
//功能属性
private Node<K,V>[] table; //存储数组
private int size; //存放节点的个数
//无参构造方法
public MyHashMap() {
//默认数组长度
this.table = new Node[10];
}
//有参构造方法
public MyHashMap(int length) {
//手动给数组定义长度
this.table = new Node[length];
}
//根据键获取值的方法
// public V get(Object key) {
//
// }
//添加方法
public void put(K key,V value) {
//计算Hash值
int num = key.hashCode();
//创建一个节点对象并赋值
Node<K, V> newNode = new Node<K,V>(key,value,putV(num),null);
if (table[newNode.hash] == null) {
table[newNode.hash] = newNode;
size++;
}else if (table[newNode.hash] != null) {
//创建一个节点指向当前元素
Node<K, V> i = newNode;
for (int j = 0;j<size;j++) {
if (j == i.hash) {
boolean flag = table[j].key.equals(i.key);
if (flag) {
table[j].key = i.key;
break;
}else {
table[j].next = i;
break;
}
}
}
}
}
//计算存储位置的方法
public int putV(int num) {
return num % 11;
}
//重写一下HashCode方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + size;
result = prime * result + Arrays.hashCode(table);
return result;
}
//重写一下比较方法
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyHashMap other = (MyHashMap) obj;
if (size != other.size)
return false;
if (!Arrays.equals(table, other.table))
return false;
return true;
}
@Override
public String toString() {
return "" + Arrays.toString(table);
}
public static void main(String[] args) {
MyHashMap<String,Integer> i = new MyHashMap<String, Integer>();
i.put("java", 123);
i.put("good", 256);
i.put("sxt", 2525);
System.out.println(i);
}
}
老师我这个相同位置。元素节点好像没有添加进去,还有那个get方法怎么写,我实在是想不出来
运行结果图:
