HashMap的小测试

测试HashMap代码:

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. /**
  4.  *
  5.  * @author ZangXT
  6.  */
  7. public class Test {
  8.     public static void main(String[] args) {
  9.         Map<String, String> map = new HashMap<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.     }

  如果对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.  * @author ZangXT
  4.  */
  5. public class Test {
  6.     public static void main(String[] args) {
  7.         String str1 = System.nanoTime() + "a";
  8.         String str2 = System.nanoTime() + "a";
  9.         String str3 = System.nanoTime() + "a";
  10.         int i1 = str1.hashCode();
  11.         int i2 = str2.hashCode();
  12.         int i3 = str3.hashCode();
  13.         int hash1 = hash(i1);
  14.         int hash2 = hash(i2);
  15.         int hash3 = hash(i3);
  16.         int index1 = indexFor(hash1, 16);
  17.         int index2 = indexFor(hash2, 16);
  18.         int index3 = indexFor(hash3, 16);
  19.         System.out.println(index1);
  20.         System.out.println(index2);
  21.         System.out.println(index3);
  22.     }
  23.     private static int hash(int h) {
  24.         h += ~(h << 9);
  25.         h ^= (h >>> 14);
  26.         h += (h << 4);
  27.         h ^= (h >>> 10);
  28.         return h;
  29.     }
  30.     static int indexFor(int h, int length) {
  31.         return h & (length - 1);
  32.     }
  33. }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值