題目:問下列代碼運行結果是什嗎?
| 代碼如下 |
複製代碼 |
|
package quiz;
public class Quiz22 {
static String str;
public static boolean test1(){
return new Boolean("1");
}
public static boolean test2(){
return new Boolean(str);
}
public static void main(String[] args) {
if(test1())
System.out.print("1");
if(!test2())
System.out.print("2");
if(test1() != test2())
System.out.print("3");
}
} |
輸出:
2
先看下Boolean類的原始碼:(部分省略了,只保留了關鍵代碼)
| 代碼如下 |
複製代碼 |
|
public final class Boolean implements java.io.Serializable, Comparable<Boolean>
{
private final boolean value;
public Boolean(boolean value) {
this.value = value;
}
public Boolean(String s) {
this(toBoolean(s));
}
public static int compare(boolean x, boolean y) {
return (x == y) ? 0 : (x ? 1 : -1);
}
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
public boolean equals(Object obj) {
if (obj instanceof Boolean) {
return value == ((Boolean)obj).booleanValue();
}
return false;
}
public int compareTo(Boolean b) {
return compare(this.value, b.value);
}
public static boolean parseBoolean(String s) {
return toBoolean(s);
}
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
/**
* Returns a {@code Boolean} with a value represented by the
* specified string. The {@code Boolean} returned represents a
* true value if the string argument is not {@code null}
* and is equal, ignoring case, to the string {@code "true"}.
*
* @param s a string.
* @return the {@code Boolean} value represented by the string.
*/
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
public String toString() {
return value ? "true" : "false";
}
/**
* Returns a hash code for this {@code Boolean} object.
*
* @return the integer {@code 1231} if this object represents
* {@code true}; returns the integer {@code 1237} if this
* object represents {@code false}.
*/
public int hashCode() {
return value ? 1231 : 1237;
}
} |
從上面可以看出:
1.Boolean支援使用String或boolean來建立對象。
如果是用boolean構建的,則Boolean對象自動拆箱後還是原來的值。
如果是用string來構建對象,則如果該String為null或string.equalsIgnoreCase("true")返回false,則Boolean拆箱後的值就為false。
2.Boolean類實現了Comparable介面,即實現了ComparaTo方法
分析題目:
test1() 等價於 (new Boolean("1")) + 自動拆箱 ,則為 false
!test2()等價於 ! (new Boolean(str) + 自動拆箱) ,因為str為null,所以結果true。
test1() != test2() ,結果為 false
如果test1和test2方法的傳回值不是boolean,而是Boolean對象,則結果就不一樣了。因為是new兩個對象,地址肯定不同,而且Boolean代碼中不想Integer有cache。
| 代碼如下 |
複製代碼 |
|
public class DecoratorPatternEx {
public static void main(String[] args) {
Boolean a = new Boolean("1");
Boolean b = new Boolean("1");
Boolean a1 = new Boolean(true);
Boolean b1 = new Boolean(true);
if ( a == b){
System.out.println( true);
}else {
System.out.println(false);
}
if ( a1 == b1){
System.out.println( true);
}else {
System.out.println(false);
}
}
} |
結果:
false
false