/** * Created by chengbx on 2018/5/19. * 简单版 */public class CbxMap { CbxEntry [] cbxEntries = new CbxEntry[999]; int size; public void put(Object key,Object value){ //解决键重复的问题 for (int i = 0; i < size; i++) { if(cbxEntries[i].getKey().equals(key)){ cbxEntries[i].setValue(value); return ; } } CbxEntry cbxEntry = new CbxEntry(key,value); cbxEntries[size++] = cbxEntry; } public Object get(Object key){ for (int i = 0; i < size; i++) { if(cbxEntries[i].getKey().equals(key)){ return cbxEntries[i].getValue(); } } return null; } public boolean containsKey(Object key){ for (int i = 0; i < size; i++) { if(cbxEntries[i].getKey().equals(key)){ return true; } } return false; } public boolean containsValue(Object value){ for (int i = 0; i < size; i++) { if(cbxEntries[i].getValue().equals(value)){ return true; } } return false; }}class CbxEntry{ private Object key; private Object value; public Object getKey() { return key; } public void setKey(Object key) { this.key = key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public CbxEntry(Object key, Object value) { this.key = key; this.value = value; }}
/** * Created by chengbx on 2018/5/19. * 优化版 */public class CbxHashMap { LinkedList[] linkedArr = new LinkedList[999];//Map的底层结构就是:数组 + 链表 int size; public int getHashCodeByKey(Object key){ return key.hashCode() % linkedArr.length; } public void put(Object key,Object value){ CbxEntry cbxEntry = new CbxEntry(key,value); int arrIndex = getHashCodeByKey(key); if(linkedArr[arrIndex]==null){ LinkedList linkedList = new LinkedList(); linkedList.add(cbxEntry); linkedArr[arrIndex] = linkedList; }else{ linkedArr[arrIndex].add(cbxEntry); } } public Object get(Object key){ int arrIndex = getHashCodeByKey(key); if(linkedArr[arrIndex]!=null){ LinkedList linkedList= linkedArr[arrIndex]; for (int i = 0; i