※ 引述《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