java hashmap value_java中HashMap的keySet()和values()

我们通常说,keySet()返回所有的键,values()返回所有的值,其实是不太对的,因为无论是keySet()和values(),其实都没有实质的内容,且容我慢慢说来。

他们前者返回了一个Set,后者返回了一个Collection,但是Set和Collection都只是接口,既然是接口,那就大有文章可以做。很重要的一点就是,接口可以不是new someClass()的来的,也就是说,它可以不对应与一个类,而只提供一些方法。实际上,HashMap中所有的数据都是放在一个Node[]的数组中的,而返回的Set接口也好,Collection也罢,都是直接针对这个Node[]数组的,所以,当使用返回的Set接口或者Collection接口进行操作是,实际上操作的还是那个Node[]数组。但是,返回的Collection只能做有限的操作,限定哪些呢?一句话总结就是:只能读,不能写,但能删能清。

不信?我们可以看源码。

首先来看values方法:

public Collectionvalues() {

Collection vs =values;if (vs == null) {

vs= newValues();

values=vs;

}returnvs;

}

可以看到values其实是返回了一个Values类的,这是个内部类,就在它后面:

final class Values extends AbstractCollection{public final int size() { returnsize; }public final void clear() { HashMap.this.clear(); }public final Iterator iterator() { return newValueIterator(); }public final boolean contains(Object o) { returncontainsValue(o); }public final Spliteratorspliterator() {return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);

}public final void forEach(Consumer super V>action) {

Node[] tab;if (action == null)throw newNullPointerException();if (size > 0 && (tab = table) != null) {int mc =modCount;for (int i = 0; i < tab.length; ++i) {for (Node e = tab[i]; e != null; e =e.next)

action.accept(e.value);

}if (modCount !=mc)throw newConcurrentModificationException();

}

}

}

看到没有,完全没有提供新数据,完全是操作那个table,或者调用hashMap自己的方法。我之前傻呵呵的找源码是怎么为values(HashMap除了有values这个方法,还有一个属性也叫values,坑爹不?)赋值的,现在才知道自己是这么傻,因为根本就没有复制嘛。

再来看keySet,也是一样的思路:

1 public SetkeySet() {2 Set ks =keySet;3 if (ks == null) {4 ks = newKeySet();5 keySet =ks;6 }7 returnks;8 }9

10 final class KeySet extends AbstractSet{11 public final int size() { returnsize; }12 public final void clear() { HashMap.this.clear(); }13 public final Iterator iterator() { return newKeyIterator(); }14 public final boolean contains(Object o) { returncontainsKey(o); }15 public final booleanremove(Object key) {16 return removeNode(hash(key), key, null, false, true) != null;17 }18 public final Spliteratorspliterator() {19 return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);20 }21 public final void forEach(Consumer super K>action) {22 Node[] tab;23 if (action == null)24 throw newNullPointerException();25 if (size > 0 && (tab = table) != null) {26 int mc =modCount;27 for (int i = 0; i < tab.length; ++i) {28 for (Node e = tab[i]; e != null; e =e.next)29 action.accept(e.key);30 }31 if (modCount !=mc)32 throw newConcurrentModificationException();33 }34 }35 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值