作者qrtt1 (愚人)
看板java
标题Re: [问题] 初学者的几点小疑问
时间Sun Jan 21 20:48:42 2007
※ 引述《war3rd (war3rd)》之铭言:
: 以下这二支小程式....
: 程式一:
: public static void main (String[] args){
: Integer n1 = new Integer(47);
: Integer n2 = new Integer(47);
: System.out.println(n1==n2);
: Integer i1 = 47;
: Integer i2 = 47;
: System.out.println(i1==i2);
: Integer p1 = 147;
: Integer p2 = 147;
: System.out.println(p1==p2);
: }
: }
: 因为小弟刚接触java(自修) 如果觉得问题太蠢还请见谅
: 问题1:为何n1==n2(结果:false)而i1==i2(结果:true) 他们的值不是都相等吗?
: 还是Integer oo = new Integer (xx) 与 Integer oo = xx 二种方式有哪不同吗?
: 问题2: 那又为啥同样是 Integer oo = xx 的方式
: i1==i2(ture) 而p1==p2(false) 这又是为啥?我只不过数字修正了一下
这是 autoboxing & unboxing 的功能,
至於为什麽改了数字就不一样了,
因为 autoboxing 後在某一段会做 value cached
(减轻产生物件的 cost)
http://java.sun.com/developer/JDCTechTips/2005/tt0405.html
<%
Autoboxing is guaranteed to return the same object for integral values in the
range [-128, 127], but an implementation may, at its discretion, cache values
outside of that range. It would be bad style to rely on this caching in your
code.
%>
不过上面的值域会依变数型态不同而不同,但还是以 jvm 实作的为准
http://javaonnet.blogspot.com/
<%
Advantage of autoboxing and auto-unboxing is concise code. But careless use
might result in poor performance of the code. Certain primitives are cached
and autoboxing returns same wrapper objects. This value may depend on jvm
used, normally this value are:
1. The boolean values true and false.
2. The byte values.
3. The short and int values between -128 and 127.
4. The char values in the range '\u0000' to '\u007F'.
%>
其实再挖挖,有人在讨论这倒底是不是一个 bad style !?
http://forum.java.sun.com/thread.jspa?forumID=316&threadID=536731
(解决了旧问题,产生了新问题)
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 163.26.34.247