多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
Boolean为final修饰,不能被继承,实现了java.io.Serializable接口和Comparable&lt;Boolean&gt;接口,可以序列化和进行比较,Boolean没有无参构造器 ### 源码 ``` public final class Boolean implements java.io.Serializable, Comparable<Boolean> { // //因为Boolean就只有两个值,故直接在jvm启动时便生成这两个值并建立引用 public static final Boolean TRUE = new Boolean(true); public static final Boolean FALSE = new Boolean(false); public static final Class<Boolean> TYPE = (Class<Boolean>) Class.getPrimitiveClass("boolean"); public Boolean(boolean value) { this.value = value; } // Boolean有一个可以传入字符串的构造器,只当字符串为“true”时,value为true,其余都为false public Boolean(String s) { this(parseBoolean(s)); } public static boolean parseBoolean(String s) { // 只要name不为true,统一返回false return ((s != null) && s.equalsIgnoreCase("true")); } public boolean booleanValue() { return value; } public static Boolean valueOf(boolean b) { return (b ? TRUE : FALSE); } public static Boolean valueOf(String s) { return parseBoolean(s) ? TRUE : FALSE; } public static String toString(boolean b) { return b ? "true" : "false"; } public String toString() { return value ? "true" : "false"; } @Override public int hashCode() { // Boolean的哈希值只有固定的两个值,true为1231,false为1237 return Boolean.hashCode(value); } public static int hashCode(boolean value) { return value ? 1231 : 1237; } public boolean equals(Object obj) { if (obj instanceof Boolean) { return value == ((Boolean)obj).booleanValue(); } return false; } public static boolean getBoolean(String name) { boolean result = false; try { result = parseBoolean(System.getProperty(name)); } catch (IllegalArgumentException | NullPointerException e) { } return result; } public int compareTo(Boolean b) { return compare(this.value, b.value); } public static int compare(boolean x, boolean y) { return (x == y) ? 0 : (x ? 1 : -1); } public static boolean logicalAnd(boolean a, boolean b) { return a && b; } public static boolean logicalOr(boolean a, boolean b) { return a || b; } public static boolean logicalXor(boolean a, boolean b) { return a ^ b; } } ``` ### 总结 * 如果一个类只有有限的几种状态,考虑用几个final的静态变量来表示不同状态的实例。例如编写一个Weekday类,状态只有7个,就不要让用户写new Weekday(1),直接提供Weekday.MONDAY即可 * 推荐的形式是Boolean.TRUE或Boolean.valueOf(true)或Boolean.valueOf("true"),避免生成不必要的对象 ### 实验室 ``` Boolean boo = new Boolean(true); System.err.println(boo == Boolean.TRUE); // false ```