java hashmap 底层详细
此hashmap中使用到MyArrayList 阅读前 请先看 我写的 MyArrayList
package cn.com.test04; class MyIterator<E>{ private MyArrayList<E> li; int i=0; MyIterator(MyArrayList<E> li){ this.li=li; } public boolean hasNext(){ if(i<li.size()&&li.get(i)!=null){ return true; }else{ return false; } } public E next(){ return (E)li.get(i++); } } class MyHashMap<K,V>{ private Node[] node; MyHashMap(){ this(10); } MyHashMap(int length){ node=new Node[length]; } public void put(K k,V v){ Node oldK = getNode(k); if(oldK!=null&&oldK.key.equals(k)){ oldK.value=v; }else{ int hashCode = getHashCode(k); Node oldNode = node[hashCode]; Node newNode=new Node(k,v,oldNode,hashCode); node[hashCode]=newNode; } } public V get(K k){ return (V)getNode(k).value; } public Node getNode(K k){ int hashCode = getHashCode(k); Node oldNode = node[hashCode]; Node temp=oldNode; while(temp!=null&&temp.key!=k){ temp=temp.up; } return temp!=null?temp:null; } private int getHashCode(K k){ return k.hashCode()%node.length; } public Object[] values(){ return getKeysAndValues("values").toArray(); } public Object[] getKey(){ return getKeysAndValues("sada").toArray(); } private MyArrayList getKeysAndValues(String aa){ MyArrayList li= new MyArrayList(); MyArrayList li1= new MyArrayList(); for(int i=0;i<node.length;i++){ Node mo = node[i]; while(mo!=null){ li.add(mo.value); li1.add(mo.key); mo=mo.up; } } return aa=="values"?li:li1; } public MyIterator<K> KeyIterator(){ return new MyIterator(getKeysAndValues("sada"));// MyIterator<String> =new new MyIterator(getKeysAndValues("sada")); } class Node<K,V>{ K key; V value; Node up; int hashCode; Node(K key,V value,Node up,int hashCode){ this.key=key; this.value=value; this.up=up; this.hashCode=hashCode; } } } public class t06 { public static void main(String[] args) { //1===1 '1'==49 "1"==49 System.out.println((char)117); System.out.println("k".hashCode()%10); MyHashMap<String, String> h=new MyHashMap<String, String>(); // 可以存大量的数据 分类管理 结合arraylist And linkedList 优点 // 可以存很多种数据 // 采用键值方式存取 适度快 // 遍历结果没得顺序 当有相同的键存如数据的时候 取得此键的值 永远是最后新存入的值 h.put("a", "aaaaaaaaa"); h.put("b", "bbbbbbbbb"); h.put("k", "kkkkkkkkkkk"); h.put("u", "uuuuuuuuu"); h.put("a", "dfsdfdsgsd"); h.put("f", "fffffffffff"); h.put("h", "hhhhhhhhhhh"); System.out.println(h.get("a")+"---------------"); Object[] val = h.getKey(); int i=0; for(Object o:val){ System.out.println(h.get((String)o)+"==="+i++); } System.out.println("======================="); MyIterator<String> ke = h.KeyIterator(); while(ke.hasNext()){ System.out.println(ke.next()+"======00000"); } } }