基本类型和引用类型,装箱,拆箱等

来源:互联网 发布:mac桌面截图 编辑:程序博客网 时间:2024/06/08 09:27
          // 在java中系统认为 -128 ~ 127 之间的整数是非常常用的,都在常量池中          // 所以这些数字对应的引用类型定义为常量,存放在方法区,常量池          // boolean  类型的值也是两个常量          // 尽量不要拿引用类型做等值比较          // 基本类型 转 String : String.valueOf() 把任意的基本类型转换成对应的字符串          // String 转基本类型 : 引用类型 .parse类型();          int a11 = Integer.parseInt("1000");          double d11 = Double.parseDouble("5.5");          boolean b11 = Boolean.parseBoolean("true");          Day_1_06_Java1          /*           * 对于基本类型来说,为了放入集合,必须在堆上开辟空间保存数据,然后把对应的地址放入集合           * 为了能够把基本类型放入堆上,需要转换为引用类型。           * 系统为我们提供了8 个类,和基本类型一一对应           *           * byte -- Byte           * short -- Short           * int -- Integer           * long -- Long           * float -- Float           * double -- Double           * char -- Character           * boolean -- Boolean           *           */          int a = 10; // 在栈上存储,不能放入集合中          Integer integer = new Integer(a); // 在堆上存储,可以放入集合中          System.out.println("a: " + a + " integer: " + integer);          // 限定只能存储int 类型 Integer,必须使用基本类型对应的引用类型          ArrayList<Integer> a2 = new ArrayList<>();          // ArrayList 是引用类型,只能存在堆上          a2.add(5);          a2.add(a);          // 系统为了方便我们的使用,会自动实现基本类型和对应的引用类型之间的相互转换          System.out.println(a2.get(0));          // 系统会自动转换为对应的类型,叫做自动装箱拆箱/封包解包          int b2 = 30;          Integer integer2 = b2; //自动从 int 类型转换成 Integer // new Integer(b2);          int b3 = integer2;   // 自动从Integer 转换为 int // b2.intValue();          // 装箱/封包:基本类型转化为引用类型          // 拆箱/解包:引用类型转化为基本类型          int a3 = 30;          a2.add(a3); // 实现这个需要两步 1. Integer temp = new Integer(a3) 2. a2.add(temp);          int b4 = a2.get(0); // 1.实现这个需要两步Integer temp = a2.get(0) 2. int b4 = temp.intValue();          // 集合不能存取基本类型,只能存取对应的引用类型          // 集合泛型必须写对应的引用类型
阅读全文
0 0
原创粉丝点击