剑 毅 阁[EVOLUTION]

栽了,呵呵

11/8/2007 12:34:41 PM
         今天在一个问题上让李鲁朋给鄙视了,哈哈,不过这种旮旯的东西也没办法,了解就可以了,所以,贴一下权威的解释吧。
  源自:  http://today.java.net/lpt/a/178

Immutable Objects

Consider the following code fragment:


   Integer i1 = 100;
   Integer i2 = 100;
   Integer i3 = 1000;
   Integer i4 = 1000;
   System.out.println(i1==i2);
   System.out.println(i3==i4);

Can you guess what will be printed on the screen? If your answer is false--well, you're wrong.

In this case, J2SE 5.0 works differently. Certain ranges of values are stored as immutable objects by the Java Virtual Machine. So, in this case, the output is:

true
false

Normally, when the primitive types are boxed into the wrapper types, the JVM allocates memory and creates a new object. But for some special cases, the JVM reuses the same object.

The following is the list of primitives stored as immutable objects:

  • boolean values true and false
  • All byte values
  • short values between -128 and 127
  • int values between -128 and 127
  • char in the range \u0000 to \u007F

Comments