栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

基本数据类型和包装类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基本数据类型和包装类

基本数据类型和包装类

为什么有了基本数据类型还要使用包装类

因为类中有方法,使用包装类可以帮助我们实现不同数据类型之间的转换。

装箱/装包

装箱也叫装包,其实就是把简单数据类型转换成包装类型。

自动装箱
 public static void main(String[] args) {
        int i = 10;
        Integer a = i;
    }

这就是自动装箱

手动装箱
   public static void main(String[] args) {
        int i = 10;
        Integer a = Integer.valueOf(i);
    }

这就是手动装箱

拆箱/拆包

拆箱也叫拆包,其实就是把包装类型转换成简单数据类型

自动拆箱
public static void main(String[] args) {
       Integer a = 10;
       int i = a;//拆包
    }

这就是自动拆箱

手动拆箱
 public static void main(String[] args) {
       Integer a = 10;
      int i = a.intValue();
    }

这就是手动拆箱

注意
public static void main(String[] args) {
        Integer a = 100;
       Integer b = 100;
        System.out.println(a == b);
    }

输出为true

 public static void main(String[] args) {
        Integer a = 200;
       Integer b = 200;
        System.out.println(a == b);
    }

但是它的输出为false,我们主要看valueof的源码:

   public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

这里的low是-128,high是127,所以我们可以理解成当输入的i值是在-128<=i<=127时,直接返回的是数组里的值,当不在这个范围时,new新的对象。所以100时为true,200时为false。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659340.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号