Day18

一、HashMap深入理解

public class HashMap<K,V> extends AbstractMap<K,V>implements Map<K,V>{
    
    //操作数
    transient int modCount;//1
    //空数组的实例(长度为0的数组)
    static final Entry<?,?>[] EMPTY_TABLE = {};
    //存入数据的容器(hash数组/hash表) --  new Entry[16];
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
    //数组默认初始化容量(必须是2的幂)
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//16
    //默认负载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //数组最大长度
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //映射关系个数
    transient int size;//1
    //阈值
    int threshold;//12
    //负载因子
    final float loadFactor;//0.75
    //hash种子数
    transient int hashSeed = 0;
    
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }
    
    //initialCapacity - 16
    //loadFactor - 0.75
    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))//NaN - Not a Number
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
    }
    
    //key - new Student("林成", "2107", "001")
    //value - '男'
    public V put(K key, V value) {
        //第一次添加元素时,进入此判断
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);//阈值-12,数组初始化,获取hashSeed
        }
        if (key == null)
            return putForNullKey(value);
        //获取在key的hash+散列算法
        int hash = hash(key);
        //通过hash值计算出在数组中的下标
        int i = indexFor(hash, table.length);
        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;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }
    
    // hash- 20
    // key- new Student("林成", "2107", "001")
    // value-'男'
    //bucketIndex-2
    void addEntry(int hash, K key, V value, int bucketIndex) {
        //判断是否扩容
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
    }
    
    // hash- 20
    // key- new Student("林成", "2107", "001")
    // value-'男'
    //bucketIndex-2
    void createEntry(int hash, K key, V value, int bucketIndex) {
        //e - null
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }
    
    static int indexFor(int h, int length) {
        return h & (length-1);
    }
    
    final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            //key为String类型时,回去的hash值是有hash种子数参与的
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
    
    //toSize - 16
    private void inflateTable(int toSize) {
        
        //capacity - 16
        int capacity = roundUpToPowerOf2(toSize);//不管传什么int数据,都返回与之对应的2的幂
		//threshold - 12
        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        //初始化数组
        table = new Entry[capacity];
        //初始化hash种子数
        initHashSeedAsNeeded(capacity);
    }
    
    final boolean initHashSeedAsNeeded(int capacity) {
        boolean currentAltHashing = hashSeed != 0;
        boolean useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean switching = currentAltHashing ^ useAltHashing;
        if (switching) {
            hashSeed = useAltHashing
                ? sun.misc.Hashing.randomHashSeed(this)
                : 0;
        }
        return switching;
    }
    
    private static int roundUpToPowerOf2(int number) {
        return number >= MAXIMUM_CAPACITY
                ? MAXIMUM_CAPACITY
                : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
    }

    
    //映射关系类/节点类
    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key; ---- key
        V value; --------Entry<K,V> next;- 下一个节点的地址
        int hash; ------- key的hash值

        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }
    }
}

场景:

	HashMap<Student, Character> map = new HashMap<>();

	map.put(new Student("林成", "2107", "001"), '男');
	map.put(new Student("李科", "2107", "002"), '男');
	map.put(new Student("卢永刚", "2107", "003"), '男');

  1. JDK1.7版本,HashMap的数据结构是什么?

数组+单向链表

  1. 什么叫做Hash桶

数组中的单向链表

  1. HashMap的数组长度为什么必须是2的幂?

计算元素存在数组中下标的算法:hash值 & 数组长度-1

如果数组长度不是2的幂,减1后二进制的某一位有可能出现0,导致数组某个位置永远存不到数据

  1. HashMap的默认负载因子是多少,作用是什么?

默认负载因子是0.75

作用:数组长度*负载因子=阈值(扩容条件)

  1. HashMap的默认负载因子为什么是0.75?

取得了时间和空间的平衡

假设负载因子过大,导致数组装满后才扩容,牺牲时间,利用空间

假设负载因子过小,导致数组装载较少内容就扩容,牺牲空间,利用时间

  1. HashMax数组最大长度是多少?

1 << 30

  1. HashMap数组最大长度为什么是1 << 30?

因为数组长度必须是2的幂并且HashMap数组最大长度的变量为int类型,所有1<<30

  1. 什么叫做Hash碰撞?

两个对象的hash值一样,导致在数组中的下标一样

  1. HashMap何时扩容?

元素个数>=阈值,并且存入数据的位置不等于null

  1. HashMap扩容机制是什么?

原来的2倍

二、HashSet深入理解

public class HashSet<E> extends AbstractSet<E> implements Set<E>{
    
    private transient HashMap<E,Object> map;
    //占位符
    private static final Object PRESENT = new Object();
    
    public HashSet() {
        map = new HashMap<>();
    }
    
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
}

场景:

HashSet<Student> set = new HashSet<>();

//key-new Student("林成", "2107", "001") value-PRESENT
set.add(new Student("林成", "2107", "001"));

key-new Student("卢永刚", "2107", "002") value-PRESENT
set.add(new Student("卢永刚", "2107", "002"));

HashSet底层由HashMap实现,元素存在HashMap中key的位置

三、TreeMap深入理解

public interface SortedMap<K,V> extends Map<K,V> {}

public interface NavigableMap<K,V> extends SortedMap<K,V> {}

public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>{
    
    //外置比较器
    private Comparator comparator;
    //根节点
    private transient Entry<K,V> root;
	//元素个数
    private transient int size = 0;
	//操作数
    private transient int modCount = 0;
    
    public TreeMap(){
        comparator = null;
    }
    
    public TreeMap(Comparator comparator){
        this.comparator = comparator;
    }
    
    //key - new Student("卢永刚", '男', 29, "2107", "003")
    //value - '男'
    public V put(K key, V value) {
        //t - 林成的Entry
        Entry<K,V> t = root;
        //第一次添加元素时进入的判断
        if (t == null) {
            //key自己判断自己,目的检查Key是否为null和key所属的类是否实现Comparable接口
            compare(key, key); 

            root = new Entry<>(key, value, null);
            size=1;
            modCount++;
            return null;
        }
        //比较结果
        int cmp;
        //父节点的变量
        Entry<K,V> parent;
        //获取外置比较器
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {//执行外置比较器的排序规则 - compare()
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {//执行内置比较器的排序规则 - compareTo()
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
            // k - 卢永刚的Student对象
            Comparable<? super K> k = (Comparable<? super K>) key;
            //cmp - -2
            do {
                //parent - 李科的Entry
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        //e - 
        Entry<K,V> e = new Entry<>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        //红黑树的制衡
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }
    
    @SuppressWarnings("unchecked")
    final int compare(Object k1, Object k2) {
        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : comparator.compare((K)k1, (K)k2);
    }
    
    static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;	---------- key
        V value; --------- value
        Entry<K,V> left; - 左边节点地址
        Entry<K,V> right;- 右边节点地址
        Entry<K,V> parent; - 父节点地址
        boolean color = BLACK;

        Entry(K key, V value, Entry<K,V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }
    }
}

场景1:

TreeMap<Student, Character> map = new TreeMap<>();
		
map.put(new Student("林成", '男', 26, "2107", "001"),'男');
map.put(new Student("李科", '男', 31, "2107", "002"),'男');
map.put(new Student("卢永刚", '男', 29, "2107", "003"),'男');

场景2:

TreeMap<Student,Character> map = new TreeMap<>(new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				if(o1.equals(o2)){
					return 0;
				}
				if(o1.getName().length() != o2.getName().length()){
					return o1.getName().length() - o2.getName().length();
				}
				if(o1.getAge() != o2.getAge()){
					return o1.getAge() - o2.getAge();
				}
				return 1;
			}
		});

map.put(new Student("林成", '男', 26, "2107", "001"),'男');
map.put(new Student("李科", '男', 31, "2107", "002"),'男');
map.put(new Student("卢永刚", '男', 29, "2107", "003"),'男');

比较器的优先级别:外置比较器>内置比较器

内置比较器-Comparable:compareTo()

外置比较器-Comparator:compare()

四、TreeSet

public interface SortedSet<E> extends Set<E> {}

public interface NavigableSet<E> extends SortedSet<E> {}

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>{
    
    private transient NavigableMap<E,Object> m;
    //没用的占位符
    private static final Object PRESENT = new Object();
    
    public TreeSet() {
        this(new TreeMap<E,Object>());
    }
    
    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }
    
    TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }
    
    public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }
}

场景1:

TreeSet<Student> set = new TreeSet<>();
		
set.add(new Student("麻生希", '女', 26, "2107", "001"));
set.add(new Student("北岛玲", '女', 31, "2107", "002"));
set.add(new Student("水菜类", '女', 29, "2107", "003"));

场景2:

TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				if(o1.equals(o2)){
					return 0;
				}
				if(o1.getName().length() != o2.getName().length()){
					return o1.getName().length() - o2.getName().length();
				}
				if(o1.getAge() != o2.getAge()){
					return o1.getAge() - o2.getAge();
				}
				return 1;
			}
		});
		
set.add(new Student("吉泽明步", '女', 27, "2108", "002"));
set.add(new Student("三上悠亚", '女', 24, "2108", "003"));
set.add(new Student("麻生希", '女', 26, "2107", "001"));

TreeSet底层由TreeMap实现

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值