java集合学习一

时间:2021-02-10 07:02:54

首先看一下java集合的关系图

1.1从全面了解Java的集合关系图。常见集合  list  set map等其中我们最常用的 list  map 结合。几天说一下常见的map。map在我工作的两年里伴随着走过了好久,虽然用的很频繁,今天是第一次开始系统的整理map。

java集合学习一

1.2 这里分析的map 都是util包下面的,不包含concurrent包下面的。

常用的map实现类有 hashmap,treemap等。这一篇主要从事系统说一下hashmap的用法,和从源码的角度说一下hashmap的底层实现,hashmap 线程不安全的问题。

hashmap的主要作者Doug Lea,也是一个大神,膜拜一下。

1.2.1 看一下hashmap 的继承和实现关系,继承于AbstractMap 实现了Map Cloneable Serializable 接口如下图

 public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

可以看出hashmap 和map AbsatractMap的关系,实现了克隆和序列化。序列化是在hashmap 里面自己实现的方法readObject,writeObject(这里要说一下集合类应为有空的为了站位置,序列化得时候要吧这些都去掉,和hash的不同平台不一定一样)

1.2.2 hashmap的实现结构,hashmap就是一个Entry的数组,数组默认的初始长度是16*0.75=12;

static final int DEFAULT_INITIAL_CAPACITY = 16;

static final float DEFAULT_LOAD_FACTOR = 0.75f;

 /**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table = new Entry[DEFAULT_INITIAL_CAPACITY];
init();
}

我们再看看Entry,他是一个hashmap 的内部类,并实现了Map内部类的Entry方法。 的结构就知道Hashmap是真么放置key 和value。 Entry 里面是有一个 value next key hash  这是一个链表的结构体,

static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash; /**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
} }

从上面我们可以看出 hashmap的结构就是一个数组,数组里面放着一个链表的头指针或者null。如下图所示

java集合学习一

然后就是put(k,v) get(k),resize(n)的方法在下一章会继续。。。。。