网站建设找哪里,网站的登陆页怎么做图片,家乡ppt模板免费下载网站,app备案查询网站Java实体类不要使用基本类型
记录一下#xff0c;在项目中因为基本类型#xff0c;所产生的bug
包装类#xff1a;8种基本类型的包装类
应用场景#xff1a;数据库建立实体映射多用包装类
这两句话是重点#xff1a;就是建立实体类禁止使用基本数据量类型#xff01;…Java实体类不要使用基本类型
记录一下在项目中因为基本类型所产生的bug
包装类8种基本类型的包装类
应用场景数据库建立实体映射多用包装类
这两句话是重点就是建立实体类禁止使用基本数据量类型而用对应的包装类
为什么呢看以下场景。
/*** 8中基本类型的对应包装类* byte short int long double float boolean char* Byte Short Integer Long Double Float Boolean Character* 区别举例int其余相同* 1、int默认为0integer默认为null* 2、int是java的基本数据类型integer是int的包装类* 3、integer必须newint直接使用*//*** 场景一* 创建对应数据库的实体类字段* 1、创建一个类型type对应数据库的一个字段* 2、注意此存在严重问题基本类型都默认有值。如int 默认为0* 3、那在进行数据库新增的时候如果不填则会默认为0。* 4、会产生严重的bug应该改为包装类的引用类型*/
//错误示范
private int type;//代表类型
//正确,设置为integer类型
private Integer typeT;所以多用包装类进行赋值。
补充
/*** 场景二* 自动装箱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
/*** 自动装拆箱*/
public static void main(String[] args) {Integer integer0 127;Integer integer1 127;System.out.println(integer0 integer1);//等于trueInteger integer2 128;Integer integer3 128;System.out.println(integer2 integer3);//等于false
}/** 源码* public static Integer valueOf(int i) {* if (i Integer.IntegerCache.low i Integer.IntegerCache.high)* return Integer.IntegerCache.cache[i (-Integer.IntegerCache.low)];* return new Integer(i);* }* 通过上我们发现如果他的int值在最高和最低之间他直接返回cache内的数据* 否则 new Integer(i);* 那么最高值high 127 ,最低值low -128,* 所以在-128至127内他们引用的是缓存内的数据地址相同所以为true。超过此则为false** private static class IntegerCache {* static final int low -128;* static final int high;* static final Integer cache[];** static {* // high value may be configured by property* int h 127;* String integerCacheHighPropValue * sun.misc.VM.getSavedProperty(java.lang.Integer.IntegerCache.high);* if (integerCacheHighPropValue ! null) {* try {* int i parseInt(integerCacheHighPropValue);* i Math.max(i, 127);* // Maximum array size is Integer.MAX_VALUE* h Math.min(i, Integer.MAX_VALUE - (-low) -1);* } catch( NumberFormatException nfe) {* // If the property cannot be parsed into an int, ignore it.* }* }* high h;** cache new Integer[(high - low) 1];* int j low;* for(int k 0; k cache.length; k)* cache[k] new Integer(j);** // range [-128, 127] must be interned (JLS7 5.1.7)* assert IntegerCache.high 127;* }** private IntegerCache() {}* }**/为何封装javabean时成员变量一律都不用基本类型
Long和Integer两个包装类所声明的是对象得引用产生的变量是以对象的身份出现而long和int是两个原型的数据修饰类型所产生的只是一个值而不是一个对象。
Long和long的区别是Long可能为nulllong最少也是0。 在数据库操作的时候null和0是有区别的。
JAVA是面向对象得JAVABEAN作为一种规范使用。所以在习惯上会把它属性都包装成对象。记住。这本身就是一种规范。