使用java.lang.Integer需要注意的一个问题

本文探讨了Java 5引入的自动装箱和拆箱功能,并通过一个具体示例指出,若不注意对象初始化可能导致的空指针异常问题。强调了在使用Integer等包装类时应注意区别于基本数据类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自Java5开始,提供了基本数据类型的自动装箱、拆箱功能。

一般情况下,我们创建一个类的对象的时候是这样创建:

Class clazz = new Class(参数?);

那么,在Java5开始,创建一个Integer(举例),可以如下:

Integer i = 10;

系统为我们进行了如下操作:Integer i = new Integer(10);

自动拆箱:

Integer i = 10;

int j = i;

自动装箱和拆箱给我们日常的开发工作提供了极大的便利,但有一个问题却需要我们注意。

比如:


public class IntegerDemo {

 /**
  *
  * @author 秦慈东
  * @date Oct 30, 2014 9:42:21 AM
  */
 public static void main(String[] args) {
  Prize prize = new Prize();
  if (prize.getTotal() > prize.getMaxsum()) {
   System.out.println("over...");
  }
  else {
   System.out.println("中了一个公仔。");
   prize.setTotal(prize.getTotal()+1);
  }
 }

}

class Prize {
 private Integer total;
 private Integer maxsum;
 /**
  * @return the total
  */
 public Integer getTotal() {
  return total;
 }
 /**
  * @param total the total to set
  */
 public void setTotal(Integer total) {
  this.total = total;
 }
 /**
  * @return the maxsum
  */
 public Integer getMaxsum() {
  return maxsum;
 }
 /**
  * @param maxsum the maxsum to set
  */
 public void setMaxsum(Integer maxsum) {
  this.maxsum = maxsum;
 }
 
}

这段程序运行的结果是什么呢?答案是这个会报空指针异常!

其实也容易理解,total和maxsum都是Integer类型,是一个对象,不是基本数据类型。

所以取值或比较的时候一定要注意上面的这个问题。


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值