Wrapper类簇



Wrapper类簇。BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short这几个Wrapper类都是Number抽象类。

 

Byte, Double, Float, Integer, Long, Short每个类都有两个构造函数,一个构造函数参数是它们所对应的原始类型;另一个构造函数的参数是String。

 

非静态方法xxxValue()函数返回原始类型

 

静态方法parseXxx(String)返回原始类型

 

静态方法valueOf(String)返回包装器类型,Integer, Long, Short有另一种重载形式,两个参数,第二个参数是基数,就是进制

 

Integer和Long两个类分别有三个重载的函数:getXxxx,返回包装器类型,

 

public static Long getLong(String nm)

 

public static Long getLong(String nm, long val);

 

public static Long getLong(String nm, Long val)

 

第二个参数是默认值。

 

每个类都用一个静态方法toString(String) 将原始类型转换为字符串,Integer, Long, Short有另一种重载形式,第二个参数是基数,就是进制

 

 


 

—————————

 

1.为什么Java语言为提供两套数据类型(基本类型和Wrapper类类型)?

2.在使用基本数据类型的位置能否直接用与其对应的Wrapper类替换?

 

一个基本的, 一个是抽象的,

在必须用抽象的时候,比如所以 Collection , Map 之类的, 就要用 Wrapper,

如果是在 Class 中用 Reflection 时需要 基本类型的参数据, 用 Wrapper 就行, 会自动处理转换,

如果你明确指定要找一个基本类型为参数的方法 ,可以用 Integer.TYPE 这种方式, 或者直接用 int.class , 因为 Class 对象有个 isPrimitive () 方法, 所以 new Integer().getClass() 和 int.class 得到的是不同的东西 , JVM 会区分的.

 

测试一下:

Class c1 = new Integer(5).getClass();

Class c2 = int.class;

Class c3 = new Integer(6).getClass();

System.out.println(” C1 == C2 ? :” + (c1 == c2) + ” , C1=C3?” + (c1 == c3));

System.out.println(” C1.equals(C2) ? :” + c1.equals(c2));

System.out.println(

“Identity : C1 =” + System.identityHashCode(c1)

+ “, C2 =”+ System.identityHashCode(c2)

+ “, C3 =” + System.identityHashCode(c3));