微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HashMap深度挖掘

一、深度分析:http://www.iteye.com/topic/754887#

二、HashMap为什么快? 就是和它优雅的设计密切相关的。

HashMap<String,Double> map = new HashMap<String,Double>(2);    

  map.put("语文",80.0);    
   map.put("数学",89.0);    
  map.put("英语",78.2);

hashmap底层使用数据实现的   transient Entry[] table;

这里的table就是用来储数据的。

 static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;}

Entry包括4个变量。

原理。1.根据key得到hashcode  方法:int hash = hash(key.hashCode());

2.根据hashcode得到对应的位置 方法:int i = indexFor(hash,table.length);

这一步很关进。可以将一个key转换成一个固定的位置。这就是为什么快的原因

当需要get(o)的时候。只要根据上面1和2两步 就可以得到该key对应的value所在的位置(table数组中的位置)。可以快速取出value

 

总结 : hashmap快的原因:可以通过hash算法。将一个固定的key转换为它唯一对应的位置。三、插入重复Key值问题

http://blog.sina.com.cn/s/blog_4abbd3410101fhe7.html

今天在用到了HashMap来遍历所有非重复的Key时遇到了一个问题,在写入数据库的时候报错--主键不能重复插入。查看了好久java文档才得以解决

    自定义一个类型

class MyType {

    private String arga;

    private String argb;

 

    public MyType(String arga,String argb) {

        this.arga = arga;

        this.argb = argb;

    }

}

 

如果代码中用到类似HashMap hm = new HashMap();

那么定义两个变量  MyType mta = new MyType("aaa","bbb");

                 MyType mtb = new MyTypr("aaa","bbb");

                 hm.put(mta,"xxx");

                 hm.put(mtb,"xxx");

猜下HashMap中有几个元素?

 

答案是有两个,原因是mta和mtb放在了不同的内存地址里面,mta和mtb传进去的是引用,那么怎么样实现HashMap没有值相同的Key呢?

方法很简单:只需要重写两个函数 public boolean equals(Object obj); 和 public int hashCode()

如下:

class MyType {

    private String arga;

    private String argb;

    public MyType(String arga,String argb) {

        this.arga = arga;

        this.argb = argb;

    }

 

    public int hashCode(){                 
     return this.arga.hashCode() * this.argb.hashCode() ; 
    
   
    public boolean equals(Object obj) {   
       if (this == obj) {               
              return true;                  
               
       if (!(obj instanceof MyType)) {  
            

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐