测试HashMap代码:
- importjava.util.HashMap;
- importjava.util.Map;
- /**
- *
- *@authorZangXT
- */
- publicclassTest{
- publicstaticvoidmain(String[]args){
- Map<String,String>map=newHashMap<String,String>();
- map.put(String.valueOf(System.nanoTime())+"a","1");
- map.put(String.valueOf(System.currentTimeMillis())+"a","2");
- map.put(String.valueOf(System.currentTimeMillis())+"a","3");
- for(Map.Entry<String,String>entry:map.entrySet()){
- System.out.printf(entry.getValue());
- }
- }
- }
如果对HashMap的原理有所了解的话应该会考虑到结果是不确定的,因为"1","2","3"三个串的顺序是无法确定的.
对于HashMap重点要掌握其存储数据的方式.HashMap内部有一个transient Entry[] table;这个数组是实际用来存储数据的.需要注意的是Entry是个链式结构,后面可以链接多个Entry.table数组在构造方法中初始化,默认大小是16.
加入数据通过put方法实现.put中首先对对象的hashCode()结果进行再hash等一些列处理,得到一个index,这个index就是此对象应该存储的位置,如果table[index]中已经存在了一个要加入的对象,或者和要加入的对象equals的对象,则用新对象替换原有的对象.如果不存在,则在此位置加入该对象( 放在链表的头上) .
hash处理的过程比较麻烦,这里把代码抽取出来测试了一下:
- /**
- *
- *@authorZangXT
- */
- publicclassTest{
- publicstaticvoidmain(String[]args){
- Stringstr1=System.nanoTime()+"a";
- Stringstr2=System.nanoTime()+"a";
- Stringstr3=System.nanoTime()+"a";
- inti1=str1.hashCode();
- inti2=str2.hashCode();
- inti3=str3.hashCode();
- inthash1=hash(i1);
- inthash2=hash(i2);
- inthash3=hash(i3);
- intindex1=indexFor(hash1,16);
- intindex2=indexFor(hash2,16);
- intindex3=indexFor(hash3,16);
- System.out.println(index1);
- System.out.println(index2);
- System.out.println(index3);
- }
- privatestaticinthash(inth){
- h+=~(h<<9);
- h^=(h>>>14);
- h+=(h<<4);
- h^=(h>>>10);
- returnh;
- }
- staticintindexFor(inth,intlength){
- returnh&(length-1);
- }
- }
把上面的例子多跑几次看看结果,就知道第一个例子中的原理了.
ps:自己的语言表达能力越来越差了,不知道该怎么搞.