`
ZangXT
  • 浏览: 116496 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

HashMap小测试

阅读更多

    测试HashMap代码:

  1. importjava.util.HashMap;
  2. importjava.util.Map;
  3. /**
  4. *
  5. *@authorZangXT
  6. */
  7. publicclassTest{
  8. publicstaticvoidmain(String[]args){
  9. Map<String,String>map=newHashMap<String,String>();
  10. map.put(String.valueOf(System.nanoTime())+"a","1");
  11. map.put(String.valueOf(System.currentTimeMillis())+"a","2");
  12. map.put(String.valueOf(System.currentTimeMillis())+"a","3");
  13. for(Map.Entry<String,String>entry:map.entrySet()){
  14. System.out.printf(entry.getValue());
  15. }
  16. }
  17. }

  如果对HashMap的原理有所了解的话应该会考虑到结果是不确定的,因为"1","2","3"三个串的顺序是无法确定的.
  对于HashMap重点要掌握其存储数据的方式.HashMap内部有一个transient Entry[] table;这个数组是实际用来存储数据的.需要注意的是Entry是个链式结构,后面可以链接多个Entry.table数组在构造方法中初始化,默认大小是16.
加入数据通过put方法实现.put中首先对对象的hashCode()结果进行再hash等一些列处理,得到一个index,这个index就是此对象应该存储的位置,如果table[index]中已经存在了一个要加入的对象,或者和要加入的对象equals的对象,则用新对象替换原有的对象.如果不存在,则在此位置加入该对象( 放在链表的头上) .
hash处理的过程比较麻烦,这里把代码抽取出来测试了一下: 

  1. /**
  2. *
  3. *@authorZangXT
  4. */
  5. publicclassTest{
  6. publicstaticvoidmain(String[]args){
  7. Stringstr1=System.nanoTime()+"a";
  8. Stringstr2=System.nanoTime()+"a";
  9. Stringstr3=System.nanoTime()+"a";
  10. inti1=str1.hashCode();
  11. inti2=str2.hashCode();
  12. inti3=str3.hashCode();
  13. inthash1=hash(i1);
  14. inthash2=hash(i2);
  15. inthash3=hash(i3);
  16. intindex1=indexFor(hash1,16);
  17. intindex2=indexFor(hash2,16);
  18. intindex3=indexFor(hash3,16);
  19. System.out.println(index1);
  20. System.out.println(index2);
  21. System.out.println(index3);
  22. }
  23. privatestaticinthash(inth){
  24. h+=~(h<<9);
  25. h^=(h>>>14);
  26. h+=(h<<4);
  27. h^=(h>>>10);
  28. returnh;
  29. }
  30. staticintindexFor(inth,intlength){
  31. returnh&(length-1);
  32. }
  33. }

把上面的例子多跑几次看看结果,就知道第一个例子中的原理了.

ps:自己的语言表达能力越来越差了,不知道该怎么搞.

分享到:
评论
1 楼 dreamhunter_lan 2011-09-13  

相关推荐

Global site tag (gtag.js) - Google Analytics