装箱与拆箱

1.以Integer为例:

装箱把基本类型的数据,包装到包装类中(基本类型->包装类)

   构造方法:

         Integer(int value) 构造一个新分配的Integer对象,它表示指定的int值。

         Integer(String s) 构造一个新分配的Integer对象,它表示String参数所指示的int值。

    静态方法:

          static Integer valueOf(int i) 返回一个表示指定的int 值的Integer实例。

          static Integer valueOf(String s) 返回保存指定String值的Integer对象。

拆箱:在包装类中取出基本类型的数据(包装类->基本类型)

    成员方法:

             int intValue() 返回该Integer对象对应的int值。

2.代码举例:

public class TestMain {
    public static void main(String[] args) {
        Integer in=1;//自动装箱Integer in=new Integer(1);
        in=in+2;//自动拆箱in.intValue()+2
                //自动装箱in=new Integer()
        ArrayList<Integer> list=new ArrayList<>();
        //ArrayList无法直接存储整数(基本类型),但是可以存储包装类Integer
        list.add(1);//自动装箱list.add(new Intger(1));
        int b=list.get(0);//自动拆箱int b=list.get(0).intValue();

    }
}

3.基本类型与字符串类型之间的转换:

基本类型-->字符串(String)

  1)基本值+”’  最简单的方法(工作中常用)

  2)包装类的静态方法toString(参数),注意这里的toString方法不是Object类中的toString()重载。

    static String toString(int i)  返回一个表示指定整数的String对象

  3)String类的静态方法valueOf(参数)。

    static String valueOf(int i)  返回int参数的字符串表示形式。

字符串(String)-->基本类型

   使用包装类的静态方法parseXXX("字符串");

   Integer 类: static int parseInt(String s)

   Double 类:static double parseDouble(String s)

4.代码举例:

public class DemoInteger {
   public static void main(String[] args) {
      //基本类型->字符串(String)
      int i =100;
      String s1=i+"";
      System.out.print1n(s1+200) ;//100200
      String s2=Integer.tostring(100):
      System.out.println(s2+200);//100200
      String s3=string.valueOf(100);
      System.out.print1n(s3+200);//100200
      //字符串(String)->基本类型
      int i= Integer.parseInt(s1):
      System.out.println(i-10);
      int a=Integer.parseInt("a");//NumberFormotException
      System.out.println(a);
   }
}
原文地址:https://www.cnblogs.com/iceywu/p/12017163.html