首先定義一個接口,代碼如下 public interface JxdMap<K, V> { int size(); V put(K key, V value); V get(K key); /** * 存放鍵值對 */ interface Entry<K, V> { K getKey(); V getValue(); V setvalue(V value); } }
實現類,裏邊有註釋,可以把代碼複製進去
package com.jxd.map; import java.util.LinkedList; public class JxdHashCodeMap<K, V> implements JxdMap<K, V> { /** * 底層的鏈表爲了方便我們假設就只能存100條數據 */ private LinkedList<Node<K, V>>[] objects = new LinkedList[100]; @Override public int size() { return 0; } @Override public V put(K key, V value) { int hashcode = hash(key); LinkedList<Node<K, V>> linkedList = objects[hashcode]; Node<K, V> node = new Node<>(key, value); if (null == linkedList) {//表示這個位置是空可以直接存放數據 linkedList = new LinkedList(); linkedList.add(node); objects[hashcode] = linkedList; } else {//表示這個位置已經佔有發生Hash碰撞 for (Node<K, V> obj : linkedList) {//把這個鏈表取出來遍歷 K nodekey = obj.getKey(); if (nodekey.equals(key)) {//如果key值 obj.setvalue(value);//則把value覆蓋 return value; } } linkedList.add(node);//發生hash碰撞但是,值不一樣直接在這個鏈表後邊追加 } return value; } @Override public V get(K key) { int hashcode = hash(key); LinkedList<Node<K, V>> linkedList = objects[hashcode];//先計算hash值取出來來 for (Node<K, V> obj : linkedList) {//遍歷這個鏈表 對比一下key值是否相等 if (obj.getKey().equals(key)) {//如果相等則返回對應的value return obj.getValue(); } } return null; } /** * 用於存放數據 * @param <K> * @param <V> */ class Node<K, V> implements Entry<K, V> { private V v; private K k; public Node(K k, V v) { this.v = v; this.k = k; } @Override public K getKey() { return k; } @Override public V getValue() { return v; } @Override public V setvalue(V value) { this.v = value; return value; } } /** * 計算hashcode值 * @param key * @return */ private int hash(K key) { int hashcode = key.hashCode() % objects.length; return hashcode; } }
測試類,我們用字符串a 和Integer 類型的97 計算出hashcode都爲97 模擬發生hash碰撞
public class test { public static void main(String[] args) { JxdMap<Object,String> jxdMap = new JxdHashCodeMap<>(); Integer integer = new Integer(97); jxdMap.put("a","jiaxiaodong"); jxdMap.put("b","wuzhihong"); jxdMap.put("c","lixiaolai"); jxdMap.put(integer,"wanweigang"); System.out.println(jxdMap.get(integer)); } }