当前位置: 首页 > news >正文

34、Java 中有了基本数据类型,为什么还需要有包装类型?包装类型是啥?

文章目录

  • 一、引入(基本数据类型弊端)
  • 二、包装类
    • (1) 模拟包装类的实现
    • (2) 包装类(Wrapper Class)
    • (3) 自动装箱、自动拆箱
      • ① 自动装箱
      • ② 自动拆箱
  • 三、整数类型包装类细节 ☆

一、引入(基本数据类型弊端)

📜 对比引用类型,基本类型(byte、short、int、float、boolean …)有一些缺陷

✒️ 无法表示不存在的值(null值)

在这里插入图片描述

✏️ 假如你开了一家🏨酒店,你想统计一周的盈利💰情况(如:星期一赚💯万、星期二亏10万 …),你会怎么做 ?

✏️ 假如用基本数据类型,您可能会如下图哪样干:

在这里插入图片描述

✏️ 上图:用一个可存放7个int类型元素的数组存放盈利额。100 是盈利100万、-10 是亏损10万元。这样可以表达出酒店一周的亏损值,但如何表达星期二没有开门呢
✏️ 用数字【0】来表达: 有歧义,数字【0】也可能表达的含义是【开门了,但一个客人都没有,一点钱都没赚,也一点钱都没有亏】
✏️ 此时基本数据类型的弊端就显现了,无法表示不存在的值(null 值)


✒️基本类型的操作不够面向对象(比如用基本类型调方法)

二、包装类

📕 Java platform provides wrapper classes for each of the primitive data types. These classes “wrap” the primitive in an object.

✏️ Java 为每一个基本数据类型提供了包装类型。包装类型是对基本数据类型的封装(把基本数据类型包装为引用对象【】)


(1) 模拟包装类的实现

把基本数据类型 int 包装为引用类型:

/**
 * @author 庆医
 * @describe 把基本类型 int 包装为引用类型
 */
public class Integer_ {
    // primitive 原始的(基本类型)
    private int primitive;

    public Integer_(int primitive) {
        this.primitive = primitive;
    }

    /**
     * 返回基本类型的值
     */
    public int getPrimitive() {
        return primitive;
    }
}

使用自定义包装类型表达一周的盈利情况:

public class TestDemo {
    public static void main(String[] args) {
        /* 无法表达不存在的值 */
        // int[] weekMoney = {100, -10, 5, 123, -3, 12, 22};

        /* 使用包装类型 */
        Integer_[] weekMoney = {
                new Integer_(100),
                null, // 星期二没有开门
                new Integer_(5),
                new Integer_(123),
                new Integer_(-3),
                new Integer_(12),
                new Integer_(22),
        };

        /* 打印一周的亏损情况和开门情况 */
        for (int i = 0; i < weekMoney.length; i++) {
            if (weekMoney[i] == null) {
                System.out.println("周" + (i + 1) + ": 没有开门");
                continue;
            }

            int primitive = weekMoney[i].getPrimitive();
            System.out.println("周" + (i + 1) + ": " + primitive);
        }
    }
}

在这里插入图片描述

(2) 包装类(Wrapper Class)

✏️ Java 的java.lang包中内置了基本类型的包装类
✏️ Java 的数字类型 (byte、short、int、long、float、double) 的包装类最终都继承自抽象类java.lang.Number
✏️ char 的包装类是 Character
✏️ boolean 的包装类是 Boolean

在这里插入图片描述
在这里插入图片描述

(3) 自动装箱、自动拆箱

① 自动装箱

在这里插入图片描述

✏️ 自动装箱:Java 编译器会自动调用包装类型的 valueOf 方法,把基本类型转换为相对应的包装类型
自动装箱:

public class TestDemo {
    public static void main(String[] args) {
        // Integer i = Integer.valueOf(11);
        Integer i = 11;

        // add(Integer.valueOf(22));
        add(22);
    }

    private static void add(Integer n) {

    }
}

在这里插入图片描述

⭐️ 整数类型(Byte、Short、Integer、Long) 的包装类的valueOf方法的底层会有缓存的操作(缓存常用的数字的包装类型)


② 自动拆箱

在这里插入图片描述

✏️ 自动拆箱:Java 编译器会自动调用包装类型的 xxxValue 方法,把包装类型转换为相对应的基本类型

public class TestDemo {
    public static void main(String[] args) {
        Integer i1 = 88;
        // class java.lang.Integer
        System.out.println(i1.getClass());

        // int i2 = i1.intValue();
        int i2 = i1;

        // System.out.println(i1.intValue() == 88);
        System.out.println(i1 == 88); // output: true

        // 自动装箱
        Integer[] ints = {11, 22, 33, 44};
        int result = 0;
        for (Integer i : ints) {
            // if(i.intValue() % 2 == 0)
            if (i % 2 == 0) {
                // result += i.intValue();
                result += i;
            }
        }
        System.out.println(result);
    }
}

public class TestDemo {
    public static void main(String[] args) {
        // 自动装箱
        // Object n = Integer.valueOf(12);
        Object n = 12;
    }
}

三、整数类型包装类细节 ☆

🖊 包装类的判等不要使用 ==!=,而应该用 equals 方法

public class TestDemo {
    public static void main(String[] args) {
        Integer n1 = 88;
        Integer n2 = 88;
        Integer n3 = 888;
        Integer n4 = 888;

        System.out.println(n1 == n2); // true
        // n3 和 n4 比较的是地址值(n3 和 n4 不是同一个对象)
        System.out.println(n3 == n4); // false

        System.out.println(n1.equals(n2)); // true
        System.out.println(n3.equals(n4)); // true
    }
}

在这里插入图片描述

⭐️ 【整数类型】的包装类的 valueOf 方法不是直接创建一个包装类对象
⭐️ 会有缓存的操作(上图是 Integer 类的 valueOf 方法的底层)


public class TestDemo {
    public static void main(String[] args) {
        Integer i1 = 88;
        Integer i2 = Integer.valueOf(88);
        Integer i3 = new Integer(88);

        // true
        System.out.println(i1 == i2);
        // false
        System.out.println(i1 == i3);
    }
}

结束,如有错误,请不吝赐教!

相关文章:

  • Spring In Action 5 学习笔记 chapter8 RabbitMQ(AMQP)要点
  • K8s有状态应用(StatefulSet)之Mysql集群
  • 原生table动态数据,通过jQuery实现相同数据时候跨行合并
  • 祖国啊,情深难载
  • 纯JavaScript实现表白代码
  • SpringCloudGateway 学习笔记 - 搭建项目
  • MySQL学习笔记:一条SQL语句的执行过程
  • Springboot框架建立(1)
  • mongodb数据模型设计
  • Java学习笔记:SQLite数据库
  • 通过mockjs生成随机响应数据
  • VGG16-好莱坞明星识别
  • 《运营商劫持, 中间人攻击, 黑客入侵怎么办?》- HTTPS 技术反制
  • Vue项目的记录(七)
  • 【云原生 • Kubernetes】集群资源监控概述、监控平台的搭建
  • ES6指北【2】—— 箭头函数
  • 【笔记】你不知道的JS读书笔记——Promise
  • 【从零开始安装kubernetes-1.7.3】2.flannel、docker以及Harbor的配置以及作用
  • 【腾讯Bugly干货分享】从0到1打造直播 App
  • 230. Kth Smallest Element in a BST
  • hadoop集群管理系统搭建规划说明
  • jquery ajax学习笔记
  • js
  • nodejs调试方法
  • scrapy学习之路4(itemloder的使用)
  • Shell编程
  • SpiderData 2019年2月23日 DApp数据排行榜
  • Vue 动态创建 component
  • 从0搭建SpringBoot的HelloWorld -- Java版本
  • 读懂package.json -- 依赖管理
  • 诡异!React stopPropagation失灵
  • 记一次用 NodeJs 实现模拟登录的思路
  • 开发基于以太坊智能合约的DApp
  • 力扣(LeetCode)357
  • 区块链共识机制优缺点对比都是什么
  • 使用 Docker 部署 Spring Boot项目
  • 线性表及其算法(java实现)
  • 掌握面试——弹出框的实现(一道题中包含布局/js设计模式)
  • 主流的CSS水平和垂直居中技术大全
  • 自动记录MySQL慢查询快照脚本
  • ionic入门之数据绑定显示-1
  • 小白应该如何快速入门阿里云服务器,新手使用ECS的方法 ...
  • ​LeetCode解法汇总2808. 使循环数组所有元素相等的最少秒数
  • ​LeetCode解法汇总518. 零钱兑换 II
  • ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException
  • #define与typedef区别
  • #设计模式#4.6 Flyweight(享元) 对象结构型模式
  • (9)YOLO-Pose:使用对象关键点相似性损失增强多人姿态估计的增强版YOLO
  • (Redis使用系列) Springboot 实现Redis 同数据源动态切换db 八
  • (八)Docker网络跨主机通讯vxlan和vlan
  • (多级缓存)缓存同步
  • (二)【Jmeter】专栏实战项目靶场drupal部署
  • (非本人原创)我们工作到底是为了什么?​——HP大中华区总裁孙振耀退休感言(r4笔记第60天)...
  • (教学思路 C#之类三)方法参数类型(ref、out、parmas)
  • (九)c52学习之旅-定时器