2017-06-13 30 views
1
public class TestPass { 

int a,b; 
TestPass(int i,int j) 
{ 
    a=i; 
    b=j; 
} 
boolean equals(TestPass o) 
{ 
    if(o.a==a&&o.b==b) 
     return true; 
    else 
     return false; 
} 

}和短路操作使用對象作爲參數在Java中

class Test 
    { 
    public static void main(String[] args) 
    { 
    TestPass ob1=new TestPass(100, 22); 
    TestPass ob2=new TestPass(100, 23); 


    System.out.println("Condition="+ob1.equals(ob2)); 
} 

}

輸出:

條件=假

我不能這樣輸出找到邏輯,bcoz'if(oa == a & & ob == b)'code is used AND s hort電路運營商(& &),它只檢查運營商的左側(我認爲是這樣)。

 TestPass ob1=new TestPass(100, 22); 
     TestPass ob2=new TestPass(100, 23); 

在這裏,我給了不同的值,但我想和短路運營商(& &)只檢查左手邊,我的預期輸出是真的!我覺得我wrong.I需要澄清,期待您的幫幫我。

+0

「AND短路操作符(&&),它只檢查操作員的左手側(我認爲是)「< - 只有左手是假的。請參閱:https://stackoverflow.com/questions/9344305/what-is-short-circuiting-and-how-is-it-used-when-programming-in-java –

+1

沒有'&&'檢查左側和如果它是'真',也檢查右邊。如果一方或雙方都是「假」,則整個表達式產生「假」。 – Berger

+0

*** Enrique_Iglesias ***你是西班牙歌手嗎? :) –

回答

0

短路僅適用於如果左側是虛假。如果左側是真的,它會繼續檢查右側。

在你的情況下,o.a==a是真的,所以它檢查右邊:o.b==b是錯誤的,使得它整體上是錯誤的。

+0

我明白了。謝謝 –

0

這是關於短路的規則您需要牢記。思考它的

╔══════════╦════════════════════════════════════════════════════════════════════════╗ 
║ Operator ║       short-circuit        ║ 
╠══════════╬════════════════════════════════════════════════════════════════════════╣ 
║ A && B ║ if A==false then the B expression is never evaluated     ║ 
║ A || B ║ if A==true then the B expression is never evaluated     ║ 
╚══════════╩════════════════════════════════════════════════════════════════════════╝ 
+0

就是這樣。謝謝! –

+0

什麼???????????? –

0

一種方法是分裂如果條件

boolean equals2(TestPass o) { 
    if (o.a == a) { 
     if (o.b == b) { 
      return true; 
     } 
     return false; 
    } 
    return false; 
} 

甚至

boolean equals3(TestPass o) { 
    if (o.a == a) { 
     return o.b == b; 
    } 
    return false; 
} 

僅供參考,您的等號可以simplfied到return o.a==a&&o.b==b