Java之Map實現升級版
阿新 • • 發佈:2018-11-17
package learn.java.cn.collection; import java.util.LinkedList; /* * 思路:陣列中放list,list中放DefMap,即陣列加連結串列; * 存放時,key的hashcode值 對陣列長度求餘後作為索引值 存放到陣列中, * 這樣在,取對應的value值時,只需求出引數key的hashcode值 ,不須遍歷陣列 * 因為可能會遇到相通的餘數,此時將它們放到同一list */ public class UpMap { int size; LinkedList[] arraylist=new LinkedList[999]; public void put (Object key,Object value) { System.out.println(key.hashCode()); int index=key.hashCode()%arraylist.length; System.out.println(index); //arraylist[index]表示存入的 是DefMap 型別的列表 //java.lang.NullPointerException //先判斷是否是空連結串列 if(arraylist[index]==null) { LinkedList list=new LinkedList(); arraylist[index]=list; list.add(new DefMap(key,value)); //指向同一物件,可以先賦值 後初始化; } arraylist[index].add(new DefMap(key,value)); } public Object get(Object key) { int i; int index=key.hashCode()%arraylist.length; for ( i=0;i<arraylist[index].size();i++) { // if (arraylist[index][i].key.equals(key)) // // return arraylist[index][i].value; // error:The type of the expression must be an array type but it resolved to LinkedList //DefMap defmap=arraylist[index].get(i); /* * error:Type mismatch: cannot convert from Object to DefMap * 列表中的型別雖然是DefMap(object的子類),但list.get()方法得到的 * 是OBJect方法,不能由下自動轉化為上,即不能子類引用指向父類物件 */ DefMap defmap=(DefMap)(arraylist[index].get(i)); if(defmap.key.equals(key)) return( (DefMap)(arraylist[index].get(i))).value; } return null; } public static void main(String args[]) { UpMap testMap=new UpMap(); testMap.put("王尚權","小靜"); testMap.put("李白", "楊冪"); System.out.println(testMap.get("王尚權")); } } class DefMap { Object key; Object value; public DefMap(Object key,Object value) { this.key=key; this.value=value; } }