2010年12月15日 星期三

字串比較 equals

轉貼:Java中的equals








在Java中,
equals 必須滿足三個必要條件:
對所有不是 reference 到 null 的 x, y ,z.
1. 反身性
即 x.equals ( x ) 為true.
2.對稱性
即 x.equals ( y ) should return true if and only if y.equals ( x ) returns true.
3.遞移性
即 if x.equals ( y ) returns true and y.equals ( z ) returns true,
則 x.equals ( z ) should return true.


例題
Given that b and c refer to instances of wrapper classes, which two statements are true?
(Choose two)
A. b.equals( b ) returns true.
B. b.equals( c ) returns the same result as b == c.
C. b.eqials( c ) can return false even if c.equals( b ) returns true.
D. b.equals( c ) throws an exception if b and c are different wrapper types.
E. b.equals( c ) returns false if the type of wrapper objects being compared are different


答案是
AE

由以上三個必要條件可知..

A. true
B. false
顯然一定不對.. 當 b 及 c 參照到不同物件時,
b == c compile 就不會過了。
C. false
根據對稱性。
D. false
b.equals( c ) 即使 b 及 c 參照到不同物件時,
仍不會產生exception..除非 b 參照到 null。
E. true
 

沒有留言:

張貼留言