Java Bean 使用包装类型 还是基本类型

参考:实体类中用基本类型好,还是用包装类型好_ - 牵牛花 - 博客园

int优缺点

优点:

1.用于Bean的时候,有默认值。比如自己拼接sql增加一个User时,会方便很多,不过现在都用ORM框架,所以这也不算是优点啦。

2.两个值比较方便,使用 == 就可以了。

缺点:

  //错误
  int a1 = (Integer) null;
  //错误
  boolean x1 = (Boolean)null;
  //正确
  Integer a2 = (Integer) null;
  Boolean x2 = (Boolean)null;

阿里巴巴开发手册中写的很明确,基本类型接收NULL值有NPE风险(java.lang.NullPointerException  NPE 空值异常),而且默认值和NULL值不能传达同一种信息,

 

Integer优缺点

优点:

可以存放null,从数据库中查出值时可能会有null

缺点:

Intege不能使用 == 比较相等。

        Integer i1 = 127;
        Integer i2 = 127;
        Integer i3 = 128;
        Integer i4 = 128;
        /**
         *   public static Integer valueOf(int i) {
         if (i >= IntegerCache.low && i <= IntegerCache.high)
         return IntegerCache.cache[i + (-IntegerCache.low)];
         return new Integer(i);
         }
         */
        System.out.println("  i1 == i2 "+(i1 == i2));//true
        System.out.println("  i3 == i4 "+(i3 == i4));//false
        int i6 = 127;
        int i7 = 127;
        int i8 = 128;
        int i9 = 128;
System.out.println(
" i6 == i7 "+(i6 == i7));//true System.out.println(" i8 == i9 "+(i8 == i9));//true System.out.println(" i1 == i6 "+(i6 == i1));//true 与 int 类型的比较都是值比较 System.out.println(" i8 == i3 "+(i8 == i3));//true int i10 = new Integer(128); int i11 = new Integer(128); System.out.println(" i10 == i11 "+(i10 == i11));//true Integer i12 = new Integer(127); Integer i13 = new Integer(127); System.out.println(" i12 == i13 "+(i12 == i11));//false 对象地址比较

猜你喜欢

转载自www.cnblogs.com/alway-july/p/8118536.html