# HashMap源码分析

## 1. 概要

• HashMap是基于Map接口实现的，提供了所有Map支持的操作，并且允许key和value为null。HashMap可以近似地认为是HashTable，其差别仅在于前者允许null的key,value，并且操作不是同步的(unsynchronized)。
• capacity是指hash表中buckets的数量，而capacity的初始值是指当hash表被创建时capacity被设定的值。
• 如果有很多mapping都要存放到同一个HashMap，那么在最开始就设置一个充足的capacity比当hash表超过阈值后再rehash要高效地多。
• 请注意：所以的实现都不是synchronized的，如果有多个线程同时操作HashMap，并且有线程会修改HashMap的结构时，则必须要对此操作加synchronized标识。增加或删除HashMap中的元素都算是修改HashMap的结构，如果仅仅只是修改某个key的value则不算。
• 如果没有可以对HashMap做synchronized的对象，那么可以使用

## 2. HashMap的实现

### 2.2 实现

#### 2.2.1 java8的改进点

 java.util.HashMap 是JDK里散列的一个实现，JDK6里采用位桶+链表的形式实现，Java8里采用的是位桶+链表/红黑树的方式，this will improve the worst case performance from O(n) to O(log n).。


#### 2.2.3 hashCode和size

hash函数如下：

tab.length的大小为2的幂次方，实现：

## 4. 遍历时操作

### 4.1 遍历时remove

Removes the current element. Throws IllegalStateException if an attempt is made to call remove() that is not preceded by a call to next( ).

KeySet继承关系如下：

### 4.3 直接使用subclass遍历时不允许修改map

remove后第二遍进入for循环时会抛ConcurrentModificationException。

A good engineer has technical mastery. A great engineer has these additional qualities:

• Clear communication of complex ideas.
Can the engineer explain themselves to non-technical stakeholders, as well as other engineers? Many technically proficient engineers are not considered great because they can’t communicate their ideas.
• They love to code.
Being an engineer is a great high paying job, which is why many good developers do it. Great engineers would code even if that wasn’t the case. They keep their skills current, and they have the stamina to power through long hours because they are doing what they love.
Desire to simplify instead of making things more complex. Hard, complex challenges are often fun for developers. Great engineers want to simplify the problem instead of building something complicated.
• A strong business and product sense.
In the development of a feature, developers often need to make product decisions that aren’t covered in the spec. Their ability to make the right call depends on an understanding of why a feature is good for the business, and how products should be built.
• They focus on the highest impact items.
Good engineers get distracted. Great engineers spend their time where it matters.
• Strong social skills.
An engineer needs to effectively interact with people across the company to be great a their job. If they can only interact with other developers, then they are only good at their job.

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in trobuleshooting or you can ask me on GitHub.

single asterisks

double asterisks

• Red
• Green
• Blue
1. Bird
2. McHale
3. Parish