hashmap是一个散列表,存储的内容是键值对(key-value)映射。hashmap继承于abstractmap并实现了map、cloneable、serializable接口。
(1)hashmap不是线程安全的,同时key-value都可以为null,并且是无序的。
(2)hashmap的初始大小为16,最大大小为2的30次方,默认的加载因子是0.75。
(3)初始容量只是哈希表在创建时的容量,加载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,就需要对该哈希表进行rehash操作(重建内部的数据结构)
hashmap与map关系如下:
(1)hashmap继承于abstractmap类,实现了map接口。
(2)hashmap通过拉链法实现哈希表。几个重要的成员变量有:table,size,threshold,loadfactor,modcount。
table是一个entry[]数组类型,entry实际上是一个单向链表,hashmap的key-value都存储在这个数组中。
size是hashmap的大小,它是hashmap保存的键值对的数量。
threshold是hashmap的阈值,用于判断是否需要调整hashmap的容量,threshold的值等于容量乘以加载因子,当hashmap中存储的数据达到threshold时,就需要将hashmap的容量加倍。
loadfactor加载因子
modcount用来实现fail-fast机制。
hashmap的遍历方式:
(1)遍历hashmap的键值对:第一步是获得通过entryset()函数获得entry集合,第二步通过iterator迭代器遍历entry集合获得数据
integer iterator =map.entryset().iterator()(iterator.hasnext())
{
map.entry entry=(map.entry)iterator.next()key=(string)enrty.getkey()value=(integer)entry.getvalue()}
(2)遍历hashmap的键,通过key来获得value
=integer =inerator =map.keyset().iterator()(iterator.hasnext())
{
key=(string)iterator.next()value=(integer)map.get(key)}
(3)遍历hashmap的值:第一步根据value获得值集合,对值集合进行迭代遍历
=collection =map.values()iterator = .iterator()(iterator.hasnext())
{
value=(integer)iterator.next()}
常用的函数:
()
object ()
(object key)
(object value)
set8817e8d4bd2291481cc1067ca69329e6> ()
(object key)
()
seta8093152e673feb7aba1828c43532094 ()
(keyvalue)
(map024902c398a6aa179f04c367da6aee33 map)
(object key)
()
collectiona8093152e673feb7aba1828c43532094 ()
hashmap示例代码:
public class hello {
public void testhashmapapis()
{
random r = new random();
hashmap601754196720ae8e56f6948b6d2ab654 map = new hashmap();
map.put(one, r.nextint(10));
map.put(two, r.nextint(10));
map.put(three, r.nextint(10));
system.out.println(map:+map );
iterator iter = map.entryset().iterator();
while(iter.hasnext())
{
map.entry entry = (map.entry)iter.next();
system.out.println(key : + entry.getkey() +,value:+entry.getvalue());
}
system.out.println(size:+map.size());
system.out.println(contains key two : +map.containskey(two));
system.out.println(contains key five : +map.containskey(five));
system.out.println(contains value 0 : +map.containsvalue(new integer(0)));
map.remove(three);
system.out.println(map:+map );
map.clear();
system.out.println((map.isempty()?map is empty:map is not empty) );
}
public static void main(string[] args) {
hello hello=new hello();
hello.testhashmapapis();
}
}
运行结果:
map:{one=3, two=9, three=9}
key : one,value:3
key : two,value:9
key : three,value:9
size:3
contains key two : true
contains key five : false
contains value 0 : false
map:{one=3, two=9}
map is empty
java8中hashmap源码分析:
public class hashmap<k,v> extends abstractmap<k,v>
implements map<k,v>, cloneable, serializable {
private static final long serialversionuid = 362498820763181265l;
static final int default_initial_capacity = 1 << 4; // 初始大小为2的4次方
static final int maximum_capacity = 1 << 30;//最大为2的30次方
static final float default_load_factor = 0.75f;//加载因子是0.75
static final int treeify_threshold = 8;
static final int untreeify_threshold = 6;
static final int min_treeify_capacity = 64;
//节点类
static class node<k,v> implements map.entry<k,v> {
final int hash;
final k key;
v value;
node<k, v> next;
node(int hash, k key, v value, node<k, v> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final k getkey() {
return key;
}
public final v getvalue() {
return value;
}
public final string tostring() {
return key + "=" + value;
}
public final int hashcode() {
return objects.hashcode(key) ^ objects.hashcode(value);
}
public final v setvalue(v newvalue) {
v oldvalue = value;
value = newvalue;
return oldvalue;
}
public final boolean equals(object o) {
if (o == this)
return true;
if (o instanceof map.entry) {
map.entry<?, ?> e = (map.entry<?, ?>) o;
if (objects.equals(key, e.getkey()) &&
objects.equals(value, e.getvalue()))
return true;
}
return false;
}
}
//计算hash
static final int hash(object key) {
int h;
return (key == null) ? 0 : (h = key.hashcode()) ^ (h >>> 16);
}
//返回类
static class<?> comparableclassfor(object x) {
if (x instanceof comparable) {
class<?> c; type[] ts, as; type t; parameterizedtype p;
if ((c = x.getclass()) == string.class) // bypass checks
return c;
if ((ts = c.getgenericinterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof parameterizedtype) &&
((p = (parameterizedtype)t).getrawtype() ==
comparable.class) &&
(as = p.getactualtypearguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
@suppresswarnings({"rawtypes","unchecked"}) // for cast to comparable
static int comparecomparables(class<?> kc, object k, object x) {
return (x == null || x.getclass() != kc ? 0 :
((comparable)k).compareto(x));
}
static final int tablesizefor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= maximum_capacity) ? maximum_capacity : n + 1;
}
transient node<k,v>[] table;//数据表
transient set<map.entry<k,v>> entryset;//实体集合
transient int size;//大小
transient int modcount;//用来实现fail-fast
int threshold;//值为capacity * load factor
final float loadfactor;//hashtable的加载因子
//构造函数,初始化容量大小和加载因子
public hashmap(int initialcapacity, float loadfactor) {
if (initialcapacity < 0)
throw new illegalargumentexception("illegal initial capacity: " +
initialcapacity);
if (initialcapacity > maximum_capacity)
initialcapacity = maximum_capacity;
if (loadfactor <= 0 || float.isnan(loadfactor))
throw new illegalargumentexception("illegal load factor: " +
loadfactor);
this.loadfactor = loadfactor;
this.threshold = tablesizefor(initialcapacity);
}
//构造函数 初始化大小
public hashmap(int initialcapacity) {
this(initialcapacity, default_load_factor);
}
//使用默认的加载因子
public hashmap() {
this.loadfactor = default_load_factor; // all other fields defaulted
}
public hashmap(map<? extends k, ? extends v> m) {
this.loadfactor = default_load_factor;
putmapentries(m, false);
}
final void putmapentries(map<? extends k, ? extends v> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadfactor) + 1.0f;
int t = ((ft < (float)maximum_capacity) ?
(int)ft : maximum_capacity);
if (t > threshold)
threshold = tablesizefor(t);
}
else if (s > threshold)
resize();
for (map.entry<? extends k, ? extends v> e : m.entryset()) {
k key = e.getkey();
v value = e.getvalue();
putval(hash(key), key, value, false, evict);
}
}
}
//返回大小
public int size() {
return size;
}
//判断是否为空
public boolean isempty() {
return size == 0;
}
//通过key获得值
public v get(object key) {
node<k,v> e;
return (e = getnode(hash(key), key)) == null ? null : e.value;
}
//通过hash和key获得节点
final node<k,v> getnode(int hash, object key) {
node<k,v>[] tab; node<k,v> first, e; int n; k k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof treenode)
return ((treenode<k,v>)first).gettreenode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
//是否含有某个key
public boolean containskey(object key) {
return getnode(hash(key), key) != null;
}
//如果之前存在key的value值,则替换掉
public v put(k key, v value) {
return putval(hash(key), key, value, false, true);
}
final v putval(int hash, k key, v value, boolean onlyifabsent,
boolean evict) {
node<k,v>[] tab; node<k,v> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newnode(hash, key, value, null);
else {
node<k,v> e; k k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof treenode)
e = ((treenode<k,v>)p).puttreeval(this, tab, hash, key, value);
else {
for (int bincount = 0; ; ++bincount) {
if ((e = p.next) == null) {
p.next = newnode(hash, key, value, null);
if (bincount >= treeify_threshold - 1) // -1 for 1st
treeifybin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
v oldvalue = e.value;
if (!onlyifabsent || oldvalue == null)
e.value = value;
afternodeaccess(e);
return oldvalue;
}
}
++modcount;
if (++size > threshold)
resize();
afternodeinsertion(evict);
return null;
}
//改变大小
final node<k,v>[] resize() {
node<k,v>[] oldtab = table;
int oldcap = (oldtab == null) ? 0 : oldtab.length;
int oldthr = threshold;
int newcap, newthr = 0;
if (oldcap > 0) {
if (oldcap >= maximum_capacity) {
threshold = integer.max_value;
return oldtab;
}
else if ((newcap = oldcap << 1) < maximum_capacity &&
oldcap >= default_initial_capacity)
newthr = oldthr << 1; // double threshold
}
else if (oldthr > 0) // initial capacity was placed in threshold
newcap = oldthr;
else { // zero initial threshold signifies using defaults
newcap = default_initial_capacity;
newthr = (int)(default_load_factor * default_initial_capacity);
}
if (newthr == 0) {
float ft = (float)newcap * loadfactor;
newthr = (newcap < maximum_capacity && ft < (float)maximum_capacity ?
(int)ft : integer.max_value);
}
threshold = newthr;
@suppresswarnings({"rawtypes","unchecked"})
node<k,v>[] newtab = (node<k,v>[])new node[newcap];
table = newtab;
if (oldtab != null) {
for (int j = 0; j < oldcap; ++j) {
node<k,v> e;
if ((e = oldtab[j]) != null) {
oldtab[j] = null;
if (e.next == null)
newtab[e.hash & (newcap - 1)] = e;
else if (e instanceof treenode)
((treenode<k,v>)e).split(this, newtab, j, oldcap);
else { // preserve order
node<k,v> lohead = null, lotail = null;
node<k,v> hihead = null, hitail = null;
node<k,v> next;
do {
next = e.next;
if ((e.hash & oldcap) == 0) {
if (lotail == null)
lohead = e;
else
lotail.next = e;
lotail = e;
}
else {
if (hitail == null)
hihead = e;
else
hitail.next = e;
hitail = e;
}
} while ((e = next) != null);
if (lotail != null) {
lotail.next = null;
newtab[j] = lohead;
}
if (hitail != null) {
hitail.next = null;
newtab[j + oldcap] = hihead;
}
}
}
}
}
return newtab;
}
final void treeifybin(node<k,v>[] tab, int hash) {
int n, index; node<k,v> e;
if (tab == null || (n = tab.length) < min_treeify_capacity)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
treenode<k,v> hd = null, tl = null;
do {
treenode<k,v> p = replacementtreenode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
public void putall(map<? extends k, ? extends v> m) {
putmapentries(m, true);
}
public v remove(object key) {
node<k,v> e;
return (e = removenode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final node<k,v> removenode(int hash, object key, object value,
boolean matchvalue, boolean movable) {
node<k,v>[] tab; node<k,v> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
node<k,v> node = null, e; k k; v v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof treenode)
node = ((treenode<k,v>)p).gettreenode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchvalue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof treenode)
((treenode<k,v>)node).removetreenode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modcount;
--size;
afternoderemoval(node);
return node;
}
}
return null;
}
public void clear() {
node<k,v>[] tab;
modcount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
public boolean containsvalue(object value) {
node<k,v>[] tab; v v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (node<k,v> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
public set<k> keyset() {
set<k> ks;
return (ks = keyset) == null ? (keyset = new keyset()) : ks;
}
final class keyset extends abstractset<k> {
public final int size() { return size; }
public final void clear() { hashmap.this.clear(); }
public final iterator<k> iterator() { return new keyiterator(); }
public final boolean contains(object o) { return containskey(o); }
public final boolean remove(object key) {
return removenode(hash(key), key, null, false, true) != null;
}
public final spliterator<k> spliterator() {
return new keyspliterator<>(hashmap.this, 0, -1, 0, 0);
}
public final void foreach(consumer<? super k> action) {
node<k,v>[] tab;
if (action == null)
throw new nullpointerexception();
if (size > 0 && (tab = table) != null) {
int mc = modcount;
for (int i = 0; i < tab.length; ++i) {
for (node<k,v> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modcount != mc)
throw new concurrentmodificationexception();
}
}
}
public collection<v> values() {
collection<v> vs;
return (vs = values) == null ? (values = new values()) : vs;
}
final class values extends abstractcollection<v> {
public final int size() { return size; }
public final void clear() { hashmap.this.clear(); }
public final iterator<v> iterator() { return new valueiterator(); }
public final boolean contains(object o) { return containsvalue(o); }
public final spliterator<v> spliterator() {
return new valuespliterator<>(hashmap.this, 0, -1, 0, 0);
}
public final void foreach(consumer<? super v> action) {
node<k,v>[] tab;
if (action == null)
throw new nullpointerexception();
if (size > 0 && (tab = table) != null) {
int mc = modcount;
for (int i = 0; i < tab.length; ++i) {
for (node<k,v> e = tab[i]; e != null; e = e.next)
action.accept(e.value);
}
if (modcount != mc)
throw new concurrentmodificationexception();
}
}
}
public set<map.entry<k,v>> entryset() {
set<map.entry<k,v>> es;
return (es = entryset) == null ? (entryset = new entryset()) : es;
}
final class entryset extends abstractset<map.entry<k,v>> {
public final int size() { return size; }
public final void clear() { hashmap.this.clear(); }
public final iterator<map.entry<k,v>> iterator() {
return new entryiterator();
}
public final boolean contains(object o) {
if (!(o instanceof map.entry))
return false;
map.entry<?,?> e = (map.entry<?,?>) o;
object key = e.getkey();
node<k,v> candidate = getnode(hash(key), key);
return candidate != null && candidate.equals(e);
}
public final boolean remove(object o) {
if (o instanceof map.entry) {
map.entry<?,?> e = (map.entry<?,?>) o;
object key = e.getkey();
object value = e.getvalue();
return removenode(hash(key), key, value, true, true) != null;
}
return false;
}
public final spliterator<map.entry<k,v>> spliterator() {
return new entryspliterator<>(hashmap.this, 0, -1, 0, 0);
}
public final void foreach(consumer<? super map.entry<k,v>> action) {
node<k,v>[] tab;
if (action == null)
throw new nullpointerexception();
if (size > 0 && (tab = table) != null) {
int mc = modcount;
for (int i = 0; i < tab.length; ++i) {
for (node<k,v> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modcount != mc)
throw new concurrentmodificationexception();
}
}
}
// overrides of jdk8 map extension methods
@override
public v getordefault(object key, v defaultvalue) {
node<k,v> e;
return (e = getnode(hash(key), key)) == null ? defaultvalue : e.value;
}
@override
public v putifabsent(k key, v value) {
return putval(hash(key), key, value, true, true);
}
@override
public boolean remove(object key, object value) {
return removenode(hash(key), key, value, true, true) != null;
}
@override
public boolean replace(k key, v oldvalue, v newvalue) {
node<k,v> e; v v;
if ((e = getnode(hash(key), key)) != null &&
((v = e.value) == oldvalue || (v != null && v.equals(oldvalue)))) {
e.value = newvalue;
afternodeaccess(e);
return true;
}
return false;
}
@override
public v replace(k key, v value) {
node<k,v> e;
if ((e = getnode(hash(key), key)) != null) {
v oldvalue = e.value;
e.value = value;
afternodeaccess(e);
return oldvalue;
}
return null;
}
@override
public v computeifabsent(k key,
function<? super k, ? extends v> mappingfunction) {
if (mappingfunction == null)
throw new nullpointerexception();
int hash = hash(key);
node<k,v>[] tab; node<k,v> first; int n, i;
int bincount = 0;
treenode<k,v> t = null;
node<k,v> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof treenode)
old = (t = (treenode<k,v>)first).gettreenode(hash, key);
else {
node<k,v> e = first; k k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++bincount;
} while ((e = e.next) != null);
}
v oldvalue;
if (old != null && (oldvalue = old.value) != null) {
afternodeaccess(old);
return oldvalue;
}
}
v v = mappingfunction.apply(key);
if (v == null) {
return null;
} else if (old != null) {
old.value = v;
afternodeaccess(old);
return v;
}
else if (t != null)
t.puttreeval(this, tab, hash, key, v);
else {
tab[i] = newnode(hash, key, v, first);
if (bincount >= treeify_threshold - 1)
treeifybin(tab, hash);
}
++modcount;
++size;
afternodeinsertion(true);
return v;
}
public v computeifpresent(k key,
bifunction<? super k, ? super v, ? extends v> remappingfunction) {
if (remappingfunction == null)
throw new nullpointerexception();
node<k,v> e; v oldvalue;
int hash = hash(key);
if ((e = getnode(hash, key)) != null &&
(oldvalue = e.value) != null) {
v v = remappingfunction.apply(key, oldvalue);
if (v != null) {
e.value = v;
afternodeaccess(e);
return v;
}
else
removenode(hash, key, null, false, true);
}
return null;
}
@override
public v compute(k key,
bifunction<? super k, ? super v, ? extends v> remappingfunction) {
if (remappingfunction == null)
throw new nullpointerexception();
int hash = hash(key);
node<k,v>[] tab; node<k,v> first; int n, i;
int bincount = 0;
treenode<k,v> t = null;
node<k,v> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof treenode)
old = (t = (treenode<k,v>)first).gettreenode(hash, key);
else {
node<k,v> e = first; k k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++bincount;
} while ((e = e.next) != null);
}
}
v oldvalue = (old == null) ? null : old.value;
v v = remappingfunction.apply(key, oldvalue);
if (old != null) {
if (v != null) {
old.value = v;
afternodeaccess(old);
}
else
removenode(hash, key, null, false, true);
}
else if (v != null) {
if (t != null)
t.puttreeval(this, tab, hash, key, v);
else {
tab[i] = newnode(hash, key, v, first);
if (bincount >= treeify_threshold - 1)
treeifybin(tab, hash);
}
++modcount;
++size;
afternodeinsertion(true);
}
return v;
}
@override
public v merge(k key, v value,
bifunction<? super v, ? super v, ? extends v> remappingfunction) {
if (value == null)
throw new nullpointerexception();
if (remappingfunction == null)
throw new nullpointerexception();
int hash = hash(key);
node<k,v>[] tab; node<k,v> first; int n, i;
int bincount = 0;
treenode<k,v> t = null;
node<k,v> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof treenode)
old = (t = (treenode<k,v>)first).gettreenode(hash, key);
else {
node<k,v> e = first; k k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++bincount;
} while ((e = e.next) != null);
}
}
if (old != null) {
v v;
if (old.value != null)
v = remappingfunction.apply(old.value, value);
else
v = value;
if (v != null) {
old.value = v;
afternodeaccess(old);
}
else
removenode(hash, key, null, false, true);
return v;
}
if (value != null) {
if (t != null)
t.puttreeval(this, tab, hash, key, value);
else {
tab[i] = newnode(hash, key, value, first);
if (bincount >= treeify_threshold - 1)
treeifybin(tab, hash);
}
++modcount;
++size;
afternodeinsertion(true);
}
return value;
}
@override
public void foreach(biconsumer<? super k, ? super v> action) {
node<k,v>[] tab;
if (action == null)
throw new nullpointerexception();
if (size > 0 && (tab = table) != null) {
int mc = modcount;
for (int i = 0; i < tab.length; ++i) {
for (node<k,v> e = tab[i]; e != null; e = e.next)
action.accept(e.key, e.value);
}
if (modcount != mc)
throw new concurrentmodificationexception();
}
}
@override
public void replaceall(bifunction<? super k, ? super v, ? extends v> function) {
node<k,v>[] tab;
if (function == null)
throw new nullpointerexception();
if (size > 0 && (tab = table) != null) {
int mc = modcount;
for (int i = 0; i < tab.length; ++i) {
for (node<k,v> e = tab[i]; e != null; e = e.next) {
e.value = function.apply(e.key, e.value);
}
}
if (modcount != mc)
throw new concurrentmodificationexception();
}
}
@suppresswarnings("unchecked")
@override
public object clone() {
hashmap<k,v> result;
try {
result = (hashmap<k,v>)super.clone();
} catch (clonenotsupportedexception e) {
// this shouldn't happen, since we are cloneable
throw new internalerror(e);
}
result.reinitialize();
result.putmapentries(this, false);
return result;
}
final float loadfactor() { return loadfactor; }
final int capacity() {
return (table != null) ? table.length :
(threshold > 0) ? threshold :
default_initial_capacity;
}
private void writeobject(java.io.objectoutputstream s)
throws ioexception {
int buckets = capacity();
// write out the threshold, loadfactor, and any hidden stuff
s.defaultwriteobject();
s.writeint(buckets);
s.writeint(size);
internalwriteentries(s);
}
private void readobject(java.io.objectinputstream s)
throws ioexception, classnotfoundexception {
// read in the threshold (ignored), loadfactor, and any hidden stuff
s.defaultreadobject();
reinitialize();
if (loadfactor <= 0 || float.isnan(loadfactor))
throw new invalidobjectexception("illegal load factor: " +
loadfactor);
s.readint(); // read and ignore number of buckets
int mappings = s.readint(); // read number of mappings (size)
if (mappings < 0)
throw new invalidobjectexception("illegal mappings count: " +
mappings);
else if (mappings > 0) { // (if zero, use defaults)
// size the table using given load factor only if within
// range of 0.25...4.0
float lf = math.min(math.max(0.25f, loadfactor), 4.0f);
float fc = (float)mappings / lf + 1.0f;
int cap = ((fc < default_initial_capacity) ?
default_initial_capacity :
(fc >= maximum_capacity) ?
maximum_capacity :
tablesizefor((int)fc));
float ft = (float)cap * lf;
threshold = ((cap < maximum_capacity && ft < maximum_capacity) ?
(int)ft : integer.max_value);
@suppresswarnings({"rawtypes","unchecked"})
node<k,v>[] tab = (node<k,v>[])new node[cap];
table = tab;
// read the keys and values, and put the mappings in the hashmap
for (int i = 0; i < mappings; i++) {
@suppresswarnings("unchecked")
k key = (k) s.readobject();
@suppresswarnings("unchecked")
v value = (v) s.readobject();
putval(hash(key), key, value, false, false);
}
}
}
abstract class hashiterator {
node<k,v> next; // next entry to return
node<k,v> current; // current entry
int expectedmodcount; // for fast-fail
int index; // current slot
hashiterator() {
expectedmodcount = modcount;
node<k,v>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
public final boolean hasnext() {
return next != null;
}
final node<k,v> nextnode() {
node<k,v>[] t;
node<k,v> e = next;
if (modcount != expectedmodcount)
throw new concurrentmodificationexception();
if (e == null)
throw new nosuchelementexception();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
public final void remove() {
node<k,v> p = current;
if (p == null)
throw new illegalstateexception();
if (modcount != expectedmodcount)
throw new concurrentmodificationexception();
current = null;
k key = p.key;
removenode(hash(key), key, null, false, false);
expectedmodcount = modcount;
}
}
final class keyiterator extends hashiterator
implements iterator<k> {
public final k next() { return nextnode().key; }
}
final class valueiterator extends hashiterator
implements iterator<v> {
public final v next() { return nextnode().value; }
}
final class entryiterator extends hashiterator
implements iterator<map.entry<k,v>> {
public final map.entry<k,v> next() { return nextnode(); }
}
static class hashmapspliterator<k,v> {
final hashmap<k,v> map;
node<k,v> current; // current node
int index; // current index, modified on advance/split
int fence; // one past last index
int est; // size estimate
int expectedmodcount; // for comodification checks
hashmapspliterator(hashmap<k,v> m, int origin,
int fence, int est,
int expectedmodcount) {
this.map = m;
this.index = origin;
this.fence = fence;
this.est = est;
this.expectedmodcount = expectedmodcount;
}
final int getfence() { // initialize fence and size on first use
int hi;
if ((hi = fence) < 0) {
hashmap<k,v> m = map;
est = m.size;
expectedmodcount = m.modcount;
node<k,v>[] tab = m.table;
hi = fence = (tab == null) ? 0 : tab.length;
}
return hi;
}
public final long estimatesize() {
getfence(); // force init
return (long) est;
}
}
static final class keyspliterator<k,v>
extends hashmapspliterator<k,v>
implements spliterator<k> {
keyspliterator(hashmap<k,v> m, int origin, int fence, int est,
int expectedmodcount) {
super(m, origin, fence, est, expectedmodcount);
}
public keyspliterator<k,v> trysplit() {
int hi = getfence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new keyspliterator<>(map, lo, index = mid, est >>>= 1,
expectedmodcount);
}
public void foreachremaining(consumer<? super k> action) {
int i, hi, mc;
if (action == null)
throw new nullpointerexception();
hashmap<k,v> m = map;
node<k,v>[] tab = m.table;
if ((hi = fence) < 0) {
mc = expectedmodcount = m.modcount;
hi = fence = (tab == null) ? 0 : tab.length;
}
else
mc = expectedmodcount;
if (tab != null && tab.length >= hi &&
(i = index) >= 0 && (i < (index = hi) || current != null)) {
node<k,v> p = current;
current = null;
do {
if (p == null)
p = tab[i++];
else {
action.accept(p.key);
p = p.next;
}
} while (p != null || i < hi);
if (m.modcount != mc)
throw new concurrentmodificationexception();
}
}
public boolean tryadvance(consumer<? super k> action) {
int hi;
if (action == null)
throw new nullpointerexception();
node<k,v>[] tab = map.table;
if (tab != null && tab.length >= (hi = getfence()) && index >= 0) {
while (current != null || index < hi) {
if (current == null)
current = tab[index++];
else {
k k = current.key;
current = current.next;
action.accept(k);
if (map.modcount != expectedmodcount)
throw new concurrentmodificationexception();
return true;
}
}
}
return false;
}
public int characteristics() {
return (fence < 0 || est == map.size ? spliterator.sized : 0) |
spliterator.distinct;
}
}
static final class valuespliterator<k,v>
extends hashmapspliterator<k,v>
implements spliterator<v> {
valuespliterator(hashmap<k,v> m, int origin, int fence, int est,
int expectedmodcount) {
super(m, origin, fence, est, expectedmodcount);
}
public valuespliterator<k,v> trysplit() {
int hi = getfence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new valuespliterator<>(map, lo, index = mid, est >>>= 1,
expectedmodcount);
}
public void foreachremaining(consumer<? super v> action) {
int i, hi, mc;
if (action == null)
throw new nullpointerexception();
hashmap<k,v> m = map;
node<k,v>[] tab = m.table;
if ((hi = fence) < 0) {
mc = expectedmodcount = m.modcount;
hi = fence = (tab == null) ? 0 : tab.length;
}
else
mc = expectedmodcount;
if (tab != null && tab.length >= hi &&
(i = index) >= 0 && (i < (index = hi) || current != null)) {
node<k,v> p = current;
current = null;
do {
if (p == null)
p = tab[i++];
else {
action.accept(p.value);
p = p.next;
}
} while (p != null || i < hi);
if (m.modcount != mc)
throw new concurrentmodificationexception();
}
}
public boolean tryadvance(consumer<? super v> action) {
int hi;
if (action == null)
throw new nullpointerexception();
node<k,v>[] tab = map.table;
if (tab != null && tab.length >= (hi = getfence()) && index >= 0) {
while (current != null || index < hi) {
if (current == null)
current = tab[index++];
else {
v v = current.value;
current = current.next;
action.accept(v);
if (map.modcount != expectedmodcount)
throw new concurrentmodificationexception();
return true;
}
}
}
return false;
}
public int characteristics() {
return (fence < 0 || est == map.size ? spliterator.sized : 0);
}
}
static final class entryspliterator<k,v>
extends hashmapspliterator<k,v>
implements spliterator<map.entry<k,v>> {
entryspliterator(hashmap<k,v> m, int origin, int fence, int est,
int expectedmodcount) {
super(m, origin, fence, est, expectedmodcount);
}
public entryspliterator<k,v> trysplit() {
int hi = getfence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new entryspliterator<>(map, lo, index = mid, est >>>= 1,
expectedmodcount);
}
public void foreachremaining(consumer<? super map.entry<k,v>> action) {
int i, hi, mc;
if (action == null)
throw new nullpointerexception();
hashmap<k,v> m = map;
node<k,v>[] tab = m.table;
if ((hi = fence) < 0) {
mc = expectedmodcount = m.modcount;
hi = fence = (tab == null) ? 0 : tab.length;
}
else
mc = expectedmodcount;
if (tab != null && tab.length >= hi &&
(i = index) >= 0 && (i < (index = hi) || current != null)) {
node<k,v> p = current;
current = null;
do {
if (p == null)
p = tab[i++];
else {
action.accept(p);
p = p.next;
}
} while (p != null || i < hi);
if (m.modcount != mc)
throw new concurrentmodificationexception();
}
}
public boolean tryadvance(consumer<? super map.entry<k,v>> action) {
int hi;
if (action == null)
throw new nullpointerexception();
node<k,v>[] tab = map.table;
if (tab != null && tab.length >= (hi = getfence()) && index >= 0) {
while (current != null || index < hi) {
if (current == null)
current = tab[index++];
else {
node<k,v> e = current;
current = current.next;
action.accept(e);
if (map.modcount != expectedmodcount)
throw new concurrentmodificationexception();
return true;
}
}
}
return false;
}
public int characteristics() {
return (fence < 0 || est == map.size ? spliterator.sized : 0) |
spliterator.distinct;
}
}
node<k,v> newnode(int hash, k key, v value, node<k,v> next) {
return new node<>(hash, key, value, next);
}
// for conversion from treenodes to plain nodes
node<k,v> replacementnode(node<k,v> p, node<k,v> next) {
return new node<>(p.hash, p.key, p.value, next);
}
// create a tree bin node
treenode<k,v> newtreenode(int hash, k key, v value, node<k,v> next) {
return new treenode<>(hash, key, value, next);
}
// for treeifybin
treenode<k,v> replacementtreenode(node<k,v> p, node<k,v> next) {
return new treenode<>(p.hash, p.key, p.value, next);
}
void reinitialize() {
table = null;
entryset = null;
keyset = null;
values = null;
modcount = 0;
threshold = 0;
size = 0;
}
// callbacks to allow linkedhashmap post-actions
void afternodeaccess(node<k,v> p) { }
void afternodeinsertion(boolean evict) { }
void afternoderemoval(node<k,v> p) { }
// called only from writeobject, to ensure compatible ordering.
void internalwriteentries(java.io.objectoutputstream s) throws ioexception {
node<k,v>[] tab;
if (size > 0 && (tab = table) != null) {
for (int i = 0; i < tab.length; ++i) {
for (node<k,v> e = tab[i]; e != null; e = e.next) {
s.writeobject(e.key);
s.writeobject(e.value);
}
}
}
}
static final class treenode<k,v> extends linkedhashmap.entry<k,v> {
treenode<k,v> parent; // red-black tree links
treenode<k,v> left;
treenode<k,v> right;
treenode<k,v> prev; // needed to unlink next upon deletion
boolean red;
treenode(int hash, k key, v val, node<k,v> next) {
super(hash, key, val, next);
}
/**
* returns root of tree containing this node.
*/
final treenode<k,v> root() {
for (treenode<k,v> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
/**
* ensures that the given root is the first node of its bin.
*/
static <k,v> void moveroottofront(node<k,v>[] tab, treenode<k,v> root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
treenode<k,v> first = (treenode<k,v>)tab[index];
if (root != first) {
node<k,v> rn;
tab[index] = root;
treenode<k,v> rp = root.prev;
if ((rn = root.next) != null)
((treenode<k,v>)rn).prev = rp;
if (rp != null)
rp.next = rn;
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkinvariants(root);
}
}
final treenode<k,v> find(int h, object k, class<?> kc) {
treenode<k,v> p = this;
do {
int ph, dir; k pk;
treenode<k,v> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableclassfor(k)) != null) &&
(dir = comparecomparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
final treenode<k,v> gettreenode(int h, object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
static int tiebreakorder(object a, object b) {
int d;
if (a == null || b == null ||
(d = a.getclass().getname().
compareto(b.getclass().getname())) == 0)
d = (system.identityhashcode(a) <= system.identityhashcode(b) ?
-1 : 1);
return d;
}
final void treeify(node<k,v>[] tab) {
treenode<k,v> root = null;
for (treenode<k,v> x = this, next; x != null; x = next) {
next = (treenode<k,v>)x.next;
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
k k = x.key;
int h = x.hash;
class<?> kc = null;
for (treenode<k,v> p = root;;) {
int dir, ph;
k pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableclassfor(k)) == null) ||
(dir = comparecomparables(kc, k, pk)) == 0)
dir = tiebreakorder(k, pk);
treenode<k,v> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
root = balanceinsertion(root, x);
break;
}
}
}
}
moveroottofront(tab, root);
}
final node<k,v> untreeify(hashmap<k,v> map) {
node<k,v> hd = null, tl = null;
for (node<k,v> q = this; q != null; q = q.next) {
node<k,v> p = map.replacementnode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}
final treenode<k,v> puttreeval(hashmap<k,v> map, node<k,v>[] tab,
int h, k k, v v) {
class<?> kc = null;
boolean searched = false;
treenode<k,v> root = (parent != null) ? root() : this;
for (treenode<k,v> p = root;;) {
int dir, ph; k pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableclassfor(k)) == null) ||
(dir = comparecomparables(kc, k, pk)) == 0) {
if (!searched) {
treenode<k,v> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tiebreakorder(k, pk);
}
treenode<k,v> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
node<k,v> xpn = xp.next;
treenode<k,v> x = map.newtreenode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((treenode<k,v>)xpn).prev = x;
moveroottofront(tab, balanceinsertion(root, x));
return null;
}
}
}
final void removetreenode(hashmap<k,v> map, node<k,v>[] tab,
boolean movable) {
int n;
if (tab == null || (n = tab.length) == 0)
return;
int index = (n - 1) & hash;
treenode<k,v> first = (treenode<k,v>)tab[index], root = first, rl;
treenode<k,v> succ = (treenode<k,v>)next, pred = prev;
if (pred == null)
tab[index] = first = succ;
else
pred.next = succ;
if (succ != null)
succ.prev = pred;
if (first == null)
return;
if (root.parent != null)
root = root.root();
if (root == null || root.right == null ||
(rl = root.left) == null || rl.left == null) {
tab[index] = first.untreeify(map); // too small
return;
}
treenode<k,v> p = this, pl = left, pr = right, replacement;
if (pl != null && pr != null) {
treenode<k,v> s = pr, sl;
while ((sl = s.left) != null) // find successor
s = sl;
boolean c = s.red; s.red = p.red; p.red = c; // swap colors
treenode<k,v> sr = s.right;
treenode<k,v> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
}
else {
treenode<k,v> sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
if ((s.parent = pp) == null)
root = s;
else if (p == pp.left)
pp.left = s;
else
pp.right = s;
if (sr != null)
replacement = sr;
else
replacement = p;
}
else if (pl != null)
replacement = pl;
else if (pr != null)
replacement = pr;
else
replacement = p;
if (replacement != p) {
treenode<k,v> pp = replacement.parent = p.parent;
if (pp == null)
root = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}
treenode<k,v> r = p.red ? root : balancedeletion(root, replacement);
if (replacement == p) { // detach
treenode<k,v> pp = p.parent;
p.parent = null;
if (pp != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
}
}
if (movable)
moveroottofront(tab, r);
}
final void split(hashmap<k,v> map, node<k,v>[] tab, int index, int bit) {
treenode<k,v> b = this;
// relink into lo and hi lists, preserving order
treenode<k,v> lohead = null, lotail = null;
treenode<k,v> hihead = null, hitail = null;
int lc = 0, hc = 0;
for (treenode<k,v> e = b, next; e != null; e = next) {
next = (treenode<k,v>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = lotail) == null)
lohead = e;
else
lotail.next = e;
lotail = e;
++lc;
}
else {
if ((e.prev = hitail) == null)
hihead = e;
else
hitail.next = e;
hitail = e;
++hc;
}
}
if (lohead != null) {
if (lc <= untreeify_threshold)
tab[index] = lohead.untreeify(map);
else {
tab[index] = lohead;
if (hihead != null) // (else is already treeified)
lohead.treeify(tab);
}
}
if (hihead != null) {
if (hc <= untreeify_threshold)
tab[index + bit] = hihead.untreeify(map);
else {
tab[index + bit] = hihead;
if (lohead != null)
hihead.treeify(tab);
}
}
}
/* ------------------------------------------------------------ */
// red-black tree methods, all adapted from clr
static <k,v> treenode<k,v> rotateleft(treenode<k,v> root,
treenode<k,v> p) {
treenode<k,v> r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null)
rl.parent = p;
if ((pp = r.parent = p.parent) == null)
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}
static <k,v> treenode<k,v> rotateright(treenode<k,v> root,
treenode<k,v> p) {
treenode<k,v> l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}
static <k,v> treenode<k,v> balanceinsertion(treenode<k,v> root,
treenode<k,v> x) {
x.red = true;
for (treenode<k,v> xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
root = rotateleft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateright(root, xpp);
}
}
}
}
else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
root = rotateright(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateleft(root, xpp);
}
}
}
}
}
}
static <k,v> treenode<k,v> balancedeletion(treenode<k,v> root,
treenode<k,v> x) {
for (treenode<k,v> xp, xpl, xpr;;) {
if (x == null || x == root)
return root;
else if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (x.red) {
x.red = false;
return root;
}
else if ((xpl = xp.left) == x) {
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateleft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null)
x = xp;
else {
treenode<k,v> sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
}
else {
if (sr == null || !sr.red) {
if (sl != null)
sl.red = false;
xpr.red = true;
root = rotateright(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null)
sr.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateleft(root, xp);
}
x = root;
}
}
}
else { // symmetric
if (xpl != null && xpl.red) {
xpl.red = false;
xp.red = true;
root = rotateright(root, xp);
xpl = (xp = x.parent) == null ? null : xp.left;
}
if (xpl == null)
x = xp;
else {
treenode<k,v> sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
}
else {
if (sl == null || !sl.red) {
if (sr != null)
sr.red = false;
xpl.red = true;
root = rotateleft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null)
sl.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateright(root, xp);
}
x = root;
}
}
}
}
}
/**
* recursive invariant check
*/
static <k,v> boolean checkinvariants(treenode<k,v> t) {
treenode<k,v> tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (treenode<k,v>)t.next;
if (tb != null && tb.next != t)
return false;
if (tn != null && tn.prev != t)
return false;
if (tp != null && t != tp.left && t != tp.right)
return false;
if (tl != null && (tl.parent != t || tl.hash > t.hash))
return false;
if (tr != null && (tr.parent != t || tr.hash < t.hash))
return false;
if (t.red && tl != null && tl.red && tr != null && tr.red)
return false;
if (tl != null && !checkinvariants(tl))
return false;
if (tr != null && !checkinvariants(tr))
return false;
return true;
}
}
}
以上就是java集合之hashmap详解的详细内容。