为什么在写实体类的时候数据库是int类型,我们写Interger来接收,分析!

首先我们先了解什么是包装类型

  • 包装类就是把基本类型封装成对象。
  • 引用官方的话就是,JDK为我们提供了一些与基本数据类型对应的类,这些类的对象可以和基本数据类型的变量直接互相赋值,并且这些类对比基本数据类型而言具有更为强大的功能。这些类就被称为包装类型。

JDK1.5 之后 提供了自动装箱 和 自动拆箱

  • 自动装箱
public class hmh {
	// 基本数据类型转换为包装类
    public static void main(String[] args) {
        int a = 10;
        Integer b = a;
        System.out.println(b);
    }

}
  • 自动拆箱
public class hmh {
	// 包装类转换为基本数据类型
    public static void main(String[] args) {
        Integer a = 10;
        int b = a;
        System.out.println(b);
    }

}
  • 底层采用valueof()包装
  • xxxValue()解析成基本数据类型
 /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
 /**
     * Returns the value of the specified number as an {@code int},
     * which may involve rounding or truncation.
     *
     * @return  the numeric value represented by this object after conversion
     *          to type {@code int}.
     */
    public abstract int intValue();

总结:考虑业务,如果查询数据库里的值有null,则用Integer来接收
如果没有null,可以考虑用int接收。因为对象可以为空,而基本数据类型不可以。包装类可以new一个对象

int默认值为0,Integer默认值为null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值