Home  >  Q&A  >  body text

为什么java源码看起来有点语法错误

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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);

上面是hashMap的一段源码,int n,i; n是没有初始化但是怎么可以n-1呢?

PHP中文网PHP中文网2741 days ago292

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:26:55

     if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            

    In the first if judgment
    1. If the previous item ((tab=table)==null) is true, then directly execute the statement in the if and assign a value to n
    2. If the previous item is false, then Just assign a value to n (n=tab.length) first, and then determine whether it is equal to 0 (equivalent to n==0)
    --2.1 If n==0 is true, then execute the statement in if
    --2.2 If n==0 is false, then n will remain unchanged and the value is tab.length

    In fact, it is equivalent to the following string

    tab = table;
    if(tab == null){
        tab = resize();
        n = tab.length;
    }else{
        n = tab.length;
        if(n == 0){
            tab = resize();
            n = tab.length;
        }
    }
    

    You should be able to understand this. .
    The logic is that if the tab array is null or has a length of 0, then let tab equal the return value of the resize() method, and let n equal the length of tab
    If tab is not null or the length is greater than 0, then n is also Same as the length of tab

    The assignment operation in the condition is also an assignment operation

    reply
    0
  • Cancelreply