首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

这两种写法的差别

2012-12-23 
这两种写法的区别?((Integer)session.getAttribute(count)).intValue()与 (Integer)session.getAttribut

这两种写法的区别?
((Integer)session.getAttribute("count")).intValue()

与 

(Integer)session.getAttribute("count")  有神马不同?

为什么已经强制转换成了 Integer 还要加一个 intValue() ?


[解决办法]
jdk 5 可以看见很明显的效果 6有自动转换的
intValue 返回的就是一个int的值
(Integer)session.getAttribute("count")  则是一个Integer对象
[解决办法]
第一个转成Integer类型并拆箱成int类型
第二个只是转换成Integer
[解决办法]

引用:
((Integer)session.getAttribute("count")).intValue()
(Integer)session.getAttribute("count")

引用:
第一个转换成int类型,放在栈空间里
第二个转换成Integer对象,放在堆空间里
int默认值为0,Integer默认为null

6楼说得很到位。
至于为什么先Integer,后int呢?由于【session.getAttribute("count")】是Object,不能直接转int,所以需要先转Integer,然后通过intValue来转成int。

另外这里还有一个隐患,【session.getAttribute("count")】可能为空,这样再.intValue()的话就会抛空指针异常。
所以最好还是分开写,先判断一下:

Integer countI = (Integer)session.getAttribute("count");
int count = 0;
if (countI != null) {
    count = countI.intValue();
}



热点排行