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:自己的语言表达能力越来越差了,不知道该怎么搞.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值