本文章为各位介绍一篇关于java Boolean包装类工作笔记,希望这篇文章能够帮助到各位同学,有兴趣的朋友可以进来看看吧。
题目:问下列代码运行结果是什么?
代码如下 | 复制代码 |
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 { 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