ホームページ  >  に質問  >  本文

为什么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日前294

全員に返信(1)返信します

  • 伊谢尔伦

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

    リーリー

    最初のif判定
    1. 前の項目((tab=table)==null)がtrueの場合、if内の文を直接実行し、nに値を代入します
    2. 前の項目がfalseの場合、次に、まず n (n=tab.length) に値を代入し、それが 0 (n==0 と同等) かどうかを判断します
    --2.1 n==0 が true の場合、次のステートメントを実行します。 if
    --2.2 n==0 が false の場合、n は変更されず、値は tab.length

    になります。

    実際には、次の文字列と同等です

    リーリー

    これは理解できるはずです。 。
    そのロジックは、tab配列がnullまたは長さが0の場合、tabをresize()メソッドの戻り値と等しく、nをタブの長さと等しくするというものです
    tabがnullでない場合、または長さがそれより大きい場合0 より大きい場合、n もタブの長さと同じになります

    条件内の代入演算も代入演算です

    返事
    0
  • キャンセル返事