Java实体类不要使用基本类型的知识点总结
发布于 2020-7-11|
复制链接
在本篇文章里小妖给大家整理的是关于Java包装类之实体类不要使用基本类型的知识点内容,需要的朋友们可以学习下。
今天来记录一下,在项目中因为基本类型,所产生的bug包装类:8种基本类型的包装类应用场景:数据库建立实体映射多用包装类这两句话是重点:就是建立实体类禁止使用基本数据量类型!!!而用对应的包装类,为什么呢,看以下场景。JAVA代码
```java
/**
* 8中基本类型的对应包装类'
* byte short int long double float boolean char
* Byte Short Integer Long Double Float Boolean Character
* 区别:(举例int,其余相同)
* 1、int默认为0,integer默认为null
* 2、int是java的基本数据类型,integer是int的包装类
* 3、integer必须new,int直接使用
*/
/**
* 场景一:
* 创建对应数据库的实体类字段
* 1、创建一个类型(type),对应数据库的一个字段
* 2、注意:此存在严重问题,基本类型都默认有值。如int 默认为0
* 3、那在进行数据库新增的时候,如果不填,则会默认为0。
* 4、会产生严重的bug,应该改为包装类的引用类型
*/
//错误示范
private int type;//代表类型
//正确,设置为integer类型
private Integer typeT;
```
所以,多用包装类进行赋值。
补充:
```java
/**
* 场景二:
* 自动装箱And自动拆箱
*/
private void testBox() {
//原本转换方式
int t = 10;
Integer ct = new Integer(t);
int tt = ct.intValue();
int i = 10;
//自动装
Integer c = i;
//自动拆
int ic = c;
}
```
笔试题题如下?为什么一个为true,一个为false???
```xhtml
/**
* 自动装拆箱
*/
public static void main(String[] args) {
Integer integer0 = 127;
Integer integer1 = 127;
System.out.println(integer0 == integer1);//等于true
Integer integer2 = 128;
Integer integer3 = 128;
System.out.println(integer2 == integer3);//等于false
/** 源码
* public static Integer valueOf(int i) {
* if (i >= Integer.IntegerCache.low && i = 127;
* }
*
* private IntegerCache() {}
* }
*
*/
}
```