java中封装类共九个,分别是Boolean,Byte,Short,Integer,Long,Float,Double,Character,Void
其中Void对于使用者并无多大意义,也不可以构造任何对象,代码如下:
package java.lang;View Code
public final class Void {
public static final Class<Void> TYPE = Class.getPrimitiveClass("void");
private Void() {}
}
这几个封装类中,以Boolean类型最简单,Character最复杂,Character个人觉得也是整个java中最复杂的一个类,先说Boolean:
package java.lang;View Code
public final class Boolean implements java.io.Serializable,Comparable<Boolean>{
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
public static final Class<Boolean> TYPE = Class.getPrimitiveClass("boolean");
private final boolean value;
private static final long serialVersionUID = -3665804199014368530L;
public Boolean(boolean value) {
this.value = value;
}
public Boolean(String s) {
this(toBoolean(s));
}
public static boolean parseBoolean(String s) {
return toBoolean(s);
}
public boolean booleanValue() {
return value;
}
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
public static String toString(boolean b) {
return b ? "true" : "false";
}
public String toString() {
return value ? "true" : "false";
}
public int hashCode() {
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 = toBoolean(System.getProperty(name));
} catch (IllegalArgumentException e) {
} catch (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);
}
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
}
Boolean实现了Comparable接口,也就是说boolean类型本身是可以比较的,而对于boolean类型而言,在java中认为true是大于false的。示例如下:
package demo.nio;
public class BooleanDemo {
public static void main(String[] args){
System.out.println(Boolean.compare(true, false));//1 代表大于
System.out.println(Boolean.compare(false, false));//0 代表等于
System.out.println(Boolean.compare(true, true));//0 代表等于
System.out.println(Boolean.compare(false, true));//-1 代表小于
}
}
值得一提的是Boolean的hashcode是两个常数,这就保证了不管从何处new的对象,只要内部的value字段值为true,它的hashcode就是1231,为false就是1237。equals方法完全调用了内部value字段的==操作。所有的封装类型都包含了valueOf的静态函数,并且有
两个重载版本,分别是基元类型参数和字符串参数。还有一个parse函数,内部可以通过返回Cache中的数据来避免重复的装箱操作。java中对于Boolean的Cache就是 Boolean.TRUE和Boolean.FALSE两个静态字段。它们是公共类型。
public class BooleanDemo {View Code
public static void main(String[] args){
Boolean b3 = Boolean.valueOf(true);
Boolean b4 = Boolean.valueOf("true");
Boolean b5 = Boolean.parseBoolean("true");
}
}