First real Python Program  • • •  再探 InvokeDynamic       all posts in Archive

Boxing Conversion 里的灵异事件

Java 的 Boxing 是一个很基本的东西,一开始学习 Java 的数据类型就能接触到。比如, boolean 的 wrapper:Boolean; byte 的 wrapper:Byte ... ... 但凡看过Java介绍的估计没有人不知道。J2SE5开始又加入了自动包装的概念 (AutoBoxing),有些东西就变得诡异起来了。来看看下面这段代码,你能正确说出结果吗?

		int integer = 127;
		Integer obj1 = integer;
		Integer obj2 = integer;
		System.out.println(obj1 == obj2);

		integer = 128;
		Integer obj3 = integer;
		Integer obj4 = integer;
		System.out.println(obj3 == obj4);

==================请先自己思考一下==================

结果是否出乎意料? 第一个输出是 True;第二个输出是 False。仅仅从127变成128,怎么会有这样的区别?

原因可以从 The Java Language Specification, Third Edition 中找到:

下面几种情况将 Primitive type 转化为包装类,以下几种情况是我们所谓的 Boxing Conversion:

  • From type boolean to type Boolean
  • From type byte to type Byte
  • From type char to type Character
  • From type short to type Short
  • From type int to type Integer
  • From type long to type Long
  • From type float to type Float
  • From type double to type Double

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

显然即是说,Java 将较小的这段值,Cache了起来,用来重用。这应该是为某些有内存限制的环境,能够节省开销的策略。虽然有些诡异,但是都是些 Primitive 类型,其实基本不可能会影响到实际的使用。