码迷,mamicode.com
首页 > 其他好文 > 详细

HashMap集合

时间:2016-02-24 15:49:26      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:java   hashmap   

Map集合

    特点:以键值对方式存储,key不可重复 value可重复

    常见实现类 HashMap   

    HashMap的底层主要是基于数组和链表来实现的,它之所以有相当快的查询速度主要是因为它是通过计算散列码来来决定存储的位置.

     HashMap中主要是通过key的hashCode来计算hash值的,只要hashCode相同,计算出来的hash值就一样。如果存储的对象对多了,就有可能不同的对象所算出来的hash值是相同的,这就出现了所谓的hash冲突。学过数据结构的同学都知道,解决hash冲突的方法有很多,HashMap底层是通过链表来解决hash冲突的。

public class HashMap<K,V>    
        extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable{
        transient Entry[] table;//元素为内部类的对象的数组
        
        
    public V put(K key, V value) {
	    //当key为null时,调用putForNullKey方法,将value放置在数组第一个位置。
      if (key == null)
      return putForNullKey(value);
      int hash = hash(key.hashCode());//根据 key 的 keyCode 计算 Hash 值
      int i = indexFor(hash, table.length);//搜索指定hash值在对应table中的索引
      for (Entry<K,V> e = table[i]; e != null; e = e.next) {//循环Entry
         Object k;
    	  //根据hash值或者key判断相等
           if (e.hash==hash && ((k=e.key)==key||key.equals(k))) {
             V oldValue = e.value;
             e.value = value;//覆盖旧值
             e.recordAccess(this);
             return oldValue;//方法返回旧的value值
         }
      }
      modCount++;//修改次数累加
      addEntry(hash, key, value, i);
      return null;
    }
              
        
     //内部类:维护链表的内容
     //实现了Map接口中Entry接口中的方法
    static class Entry<K,V> implements Map.Entry<K,V> {  
       final K key;//保存key
       V value;    //保存value
       Entry<K,V> next;//指向下一个节点
       final int hash; //保存hash值
        
     }

map集合的遍历

方法一:

 public void get(Map<String, String> map) {
        Collection<String> c = map.values();
        Iterator it = c.iterator();
        for (; it.hasNext();) {
            System.out.println(it.next());
        }
    }

方法二:

public void getByKeySet(Map<String, String> map) {
        Set<String> key = map.keySet();
        for (Iterator it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            System.out.println(map.get(s));
        }
    }

方法三:

public void getByEntry(Map<String, String> map) {
  Set<Map.Entry<String, String>> set = map.entrySet();
  for(Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext();){
    Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
      System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

 

本文出自 “QinGuan” 博客,请务必保留此出处http://11083953.blog.51cto.com/11073953/1744621

HashMap集合

标签:java   hashmap   

原文地址:http://11083953.blog.51cto.com/11073953/1744621

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!