java包装类的作用

转载自http://zhidao.baidu.com/question/2052192149152534987.html

第一,基本数据类型之间的相互转换不是都可以制动转换的,而你强制转换又会出问题,比如String类型的转换为int类型的,那么jdk为了方便用户就提供了相应的包装类。
例子:
public class Integer{
   private int i;
   public Integer(int a){
       i =a;
   }

  public static int parseToInt(){
       return i;
   }
   public static Integer valueOf(String str){
   //封装一系列的逻辑最终将str转换成int类型的IntegerStr
        return new Integer(IntegerStr);
   }
}

上面是jdk关于Integer的一个例子 比如Integer intg = Integer.valueOf(str); int i = intg.parseToInt();
这样用户就很方便的完成了 String和int的转换 这样就方便了用户

第二,有时候一个函数需要传递一个Object的变量 而你想传递int类型的进去显然不行,怎么办呢,用到了包装类。
public void test(Object obj){
}
你想传递5进去就可以这样
test(new Integer(5));

综上所述,包装类有三个用法

一个实现基本类型之间的转换

二是便于函数传值

三就是在一些地方要用到Object的时候方便将基本数据类型装换

原文地址:https://www.cnblogs.com/rixiang/p/5082094.html