Java包装类

基本数据类型     包装类 
byte                 Byte 
boolean           Boolean 
short               Short
char                 Character 
int                   Integer

long                Long 
float                Float
double            Double 

有些情况下需要将基本类型作为对象来处理,这时就需要将其转化为包装类了。

所有的包装类(Wrapper Class)都有共同的方法,他们是:

(1)带有基本值参数并创建包装类对象的构造函数.如可以利用Integer包装类创建对象,Integer obj=new Integer(145);

(2)带有字符串参数并创建包装类对象的构造函数.如new Integer("-45.36");

(3)可生成对象基本值的typeValue方法,如obj.intValue();

(4)将字符串转换为基本值的 parseType方法,如Integer.parseInt(args[0]);

(5)生成哈稀表代码的hashCode方法,如obj.hasCode();

(6)对同一个类的两个对象进行比较的equals()方法,如obj1.eauqls(obj2);

(7)生成字符串表示法的toString()方法,如obj.toString().

转换关系:

基本类型------>包装器类
Integer obj=new Integer(145);

包装器类------>基本类型
int num=obj.intValue();

字符串------>包装器类
Integer obj=new Integer("-45.36");

包装器类------>字符串包装器类

String str=obj.toString();

字符串------>基本类型
int num=Integer.parseInt("-45.36");

基本类型------>字符串包装器类

String str=String.valueOf(5);


在一定的场合,运用java包装类来解决问题,能大大提高编程效率.

JDK1.5的新特性:自动装包/拆包(Autoboxing/unboxing)

  自动装包:基本类型自动转为包装类. (int >> Integer)

  自动拆包:包装类自动转为基本类型. (Integer >> int)

  在JDK1.5之前,我们总是对集合不能存放基本类型而耿耿于怀,现在自动转换机制解决了我们的问题。

int a = 3;
Collection c = new ArrayList();
c.add(a);  //自动转换成Integer.

Integer b = new Integer(2);
c.add(b + 2);

  这里Integer先自动转换为int进行加法运算,然后int再次转换为Integer。



猜你喜欢

转载自blog.csdn.net/johnt25/article/details/80377548