HashSet和HashMap

来源:互联网 发布:h改编网络同人小说 编辑:程序博客网 时间:2024/06/07 01:42

HashSet与HashMap

HashSet中内置hashMap

代码块

HashSet源码中

内置hashMapprivate transient HashMap<E,Object> map;作为值的Object对象private static final Object PRESENT = new Object();

HashSet的add方法:

public boolean add(E e) {    //有原值,返回值为true。无原值,返回false    return map.put(e, PRESENT) == null;}

HashMap的put方法:

public V put(K key, V value) {    if(table == EMPTY_TABLE) {        inflateTable(threshold);    }    if(key == null)        //判断有没有null,如果有null值,替换掉        return putForNullKey(value);    int hash = hash(key);    int i = indexFor(hash, table.length);    //突然感觉java的hashMap速度真慢    for (Entry<K, V> e = table[i]; e != null; e = e.next) {        Object k;        //如果存在,就将旧指返回        if(e.hash == hash && ((k = e.key) == key || key.equals(k)) {            V oldValue = e.value;            e.value = value;            //hashMap中未实现            e.recordAccess(this);            return oldValue;        }    }    modCount ++;    addEntry(hash, key, value, i);    return null;}

也就是说如果有值,就替换为新值,返回原值。如果没有,直接添加。

另外两个序列化使用到的函数writeObject(),readObject()。
第一次做笔记,排版还需要改善,希望以后能够坚持下去。

0 0
原创粉丝点击