Re: [問題] 初學者的幾點小疑問
※ 引述《qrtt1 (foolish)》之銘言:
> : 因為小弟剛接觸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
> (解決了舊問題,產生了新問題)
題底出來了原來是物件簡併的手法以重複使用物件減少GC來提昇程式效能
import java.util.Random;
public class Test1 {
final private Random r = new Random();
public int getNumber() {
int i = r.nextInt(127);
if (r.nextBoolean())
i = i * -1;
return i;
}
public void testNew() {
int c = 9999999;
while (c-- >0) {
// 不使用簡併
new Integer(getNumber());
try {
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void testValueOf() {
int c = 9999999;
while (c-- >0) {
// 使用簡併
Integer.valueOf((getNumber()));
try {
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Test1().testValueOf();
//new Test1().testNew();
}
}
ValueOf (簡併 --> reuse)
http://farm1.static.flickr.com/210/464703162_82ca5ff60b_o.jpg

New (無簡併 --> no reuse)
http://farm1.static.flickr.com/229/464703070_51bb9346a3_o.jpg

--
我們都不知道,那些我們不知道的事情,我們就是不知道。
--
我們都不知道,那些我們不知道的事情,我們就是不知道。
--
※ Origin: SayYA 資訊站 <bbs.sayya.org>
◆ From: 211.21.79.162
討論串 (同標題文章)
java 近期熱門文章
PTT數位生活區 即時熱門文章