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

来源:互联网 发布:java多线程有什么用 编辑:程序博客网 时间:2024/06/05 09:02

自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类型,是一个对象,不是基本数据类型。

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


 

0 0
原创粉丝点击