Boolean源码解析


下面我们来学习Boolean

1
public final class Boolean implements java.io.Serializable,Comparable<Boolean>

final修饰,不会被继承,内部变量也会默认不可继承。
实现了Comparable,具有比较方法:

1
2
3
4
//相等返回0,不等X为ture返回1,否则返回-1
public static int compare(boolean x, boolean y) {
return (x == y) ? 0 : (x ? 1 : -1);
}

将最常用的值加入常量池:

1
2
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);

有一个有意思的地方,true和false的哈希码是固定的:

1
2
3
public static int hashCode(boolean value) {
return value ? 1231 : 1237;
}

因为这个原因,对boolean参数类型的equals方法做了特殊处理:

1
2
3
4
5
6
7
//哈哈,这帮人机智啊
public boolean equals(Object obj) {
if (obj instanceof Boolean) {
return value == ((Boolean)obj).booleanValue();
}
return false;
}

有一个奇葩方法:

1
2
3
4
5
6
7
8
public static boolean getBoolean(String name) {
boolean result = false;
try {
result = parseBoolean(System.getProperty(name));
} catch (IllegalArgumentException | NullPointerException e) {
}
return result;
}

研究了一会发现他没什么用…请知道应用场景的告诉我(如果说用来读配置文件就算了)

1
2
3
4
5
6
7
8
9
10
//这个名字挺有意思,快用这些东西代替 && 操作吧,1.8后才有哦
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
//平时用的最多的应该就是这个了
public static Boolean valueOf(String s) {
return parseBoolean(s) ? TRUE : FALSE;
}
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}

好了,这个类很简单,咱们快速进入下一个Byte的学习。

-------------本文结束,感谢您的阅读-------------

本文标题:Boolean源码解析

文章作者:饭饭君~

发布时间:2018年12月21日 - 14:50

最后更新:2019年04月23日 - 10:47

原始链接:https://yangcf.github.io/2018/12/21/Boolean源码解析/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

如果我的文章有帮助到你,欢迎打赏~~
0%