`
Odysseus_110
  • 浏览: 120352 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Integer中用静态内部类所作的缓存

    博客分类:
  • J2SE
阅读更多

今天在做一个题目时,发现一个奇怪的Integer方法。

public class TestingString{
	public static void main(String[] args){
      TestingString inst_test = new TestingString();
      int i1 = 128;
      int i2 = 128;
      int i3 = 2;
      int i4 = 2;
      Integer Ithree = new Integer(2); // 1
      Integer Ifour = new Integer(2); // 2
      System.out.println( Ithree == Ifour );
      inst_test.method( i3 , i4 );
      inst_test.method( i1 , i2 );
   }
   public void method( Integer i , Integer eye ) {
      System.out.println(i == eye );
   }

}

result: false
           true
           false

i3 == i4 和 i1 == i2的结果竟然不同,接着又继续测试了一下,只要i的值大于127,输出结果就是false。又翻了一下K&B's  book, 其中有一段话:

写道
为了节省内存,对于下列包装对象的两个实例,当它们的基本值相同时,他们总是==:
Boolean
Byte
Character, \u0000 - \u007f(7f是十进制的127)
Integer, -128 - 127

 这儿的Integer有一个范围,以前还没注意这儿,于是看了下Integer类中的源代码,发现其中有这么一段:

   private static class IntegerCache {
	private IntegerCache(){}

	static final Integer cache[] = new Integer[-(-128) + 127 + 1];

	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Integer(i - 128);
	}
    }

    /**
     * Returns a <tt>Integer</tt> instance representing the specified
     * <tt>int</tt> value.
     * If a new <tt>Integer</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Integer(int)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  i an <code>int</code> value.
     * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
	final int offset = 128;
	if (i >= -128 && i <= 127) { // must cache 
	    return IntegerCache.cache[i + offset];
	}
        return new Integer(i);
    }
 

 这儿的IntegerCache有一个静态的Integer数组,在类加载时就将-128 到 127 的Integer对象创建了,并保存在cache数组中,一旦程序调用valueOf 方法,如果i的值是在-128 到 127 之间就直接在cache缓存数组中去取Integer对象。

 

再看上面的程序,由于我们声明的i1, i2, i3, i4都是基本类型,在java5中,自动装箱会调用Integer.valueOf(i)来将这些基本类型包装成Integer,由于i3, i4 都是在 -128 到 127 之间,所以它们包装后的Integer对象都是从cache缓存中取出的,返回的是一个对象,所以当我们调用 i == eye 时,它们指向的是同一个cache缓存中取出的Integer对象。而 i1 i2的值大于127,valueOf(int i)方法将会为i1 i2 各自返回一个新Integer对象,所以打印出false。

 

再看其它的包装器:

Byte:(全部缓存)

    private static class ByteCache {
	private ByteCache(){}

	static final Byte cache[] = new Byte[-(-128) + 127 + 1];

	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Byte((byte)(i - 128));
	}
    }

    /**
     * Returns a <tt>Byte</tt> instance representing the specified
     * <tt>byte</tt> value.
     * If a new <tt>Byte</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Byte(byte)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  b a byte value.
     * @return a <tt>Byte</tt> instance representing <tt>b</tt>.
     * @since  1.5
     */
    public static Byte valueOf(byte b) {
	final int offset = 128;
	return ByteCache.cache[(int)b + offset];
    }

 

Short(-128 - 127缓存):

    private static class ShortCache {
	private ShortCache(){}

	static final Short cache[] = new Short[-(-128) + 127 + 1];

	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Short((short)(i - 128));
	}
    }

    /**
     * Returns a <tt>Short</tt> instance representing the specified
     * <tt>short</tt> value.
     * If a new <tt>Short</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Short(short)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  s a short value.
     * @return a <tt>Short</tt> instance representing <tt>s</tt>.
     * @since  1.5
     */
    public static Short valueOf(short s) {
	final int offset = 128;
	int sAsInt = s;
	if (sAsInt >= -128 && sAsInt <= 127) { // must cache 
	    return ShortCache.cache[sAsInt + offset];
	}
        return new Short(s);
    }

 

Long(-128 - 127缓存):

   private static class LongCache {
	private LongCache(){}

	static final Long cache[] = new Long[-(-128) + 127 + 1];

	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Long(i - 128);
	}
    }

    /**
     * Returns a <tt>Long</tt> instance representing the specified
     * <tt>long</tt> value.
     * If a new <tt>Long</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Long(long)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  l a long value.
     * @return a <tt>Long</tt> instance representing <tt>l</tt>.
     * @since  1.5
     */
    public static Long valueOf(long l) {
	final int offset = 128;
	if (l >= -128 && l <= 127) { // will cache
	    return LongCache.cache[(int)l + offset];
	}
        return new Long(l);
    }

 

Float(没有缓存):

    /**
     * Returns a <tt>Float</tt> instance representing the specified
     * <tt>float</tt> value.
     * If a new <tt>Float</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Float(float)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  f a float value.
     * @return a <tt>Float</tt> instance representing <tt>f</tt>.
     * @since  1.5
     */
    public static Float valueOf(float f) {
        return new Float(f);
    }

 

Double(没有缓存):

    /**
     * Returns a <tt>Double</tt> instance representing the specified
     * <tt>double</tt> value.
     * If a new <tt>Double</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Double(double)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  d a double value.
     * @return a <tt>Double</tt> instance representing <tt>d</tt>.
     * @since  1.5
     */
    public static Double valueOf(double d) {
        return new Double(d);
    }

 

 Character(<= 127缓存):

    private static class CharacterCache {
	private CharacterCache(){}

	static final Character cache[] = new Character[127 + 1];

	static {
	    for(int i = 0; i < cache.length; i++)
		cache[i] = new Character((char)i);
	}
    }

    /**
     * Returns a <tt>Character</tt> instance representing the specified
     * <tt>char</tt> value.
     * If a new <tt>Character</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Character(char)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  c a char value.
     * @return a <tt>Character</tt> instance representing <tt>c</tt>.
     * @since  1.5
     */
    public static Character valueOf(char c) {
	if(c <= 127) { // must cache
	    return CharacterCache.cache[(int)c];
	}
        return new Character(c);
    }

 

同样对于垃圾回收器来说:

Integer i = 100;
i = null;//will not make any object available for GC at all.
 

这里的代码不会有对象符合垃圾回收器的条件,这儿的i虽然被赋予null,但它之前指向的是cache中的Integer对象,而cache没有被赋null,所以Integer(100)这个对象还是存在。

 

而如果i大于127或小于-128则它所指向的对象将符合垃圾回收的条件:

Integer i = 10000;
i = null;//will make the newly created Integer object available for GC.
 
0
0
分享到:
评论

相关推荐

    架构脑图.pdf

    - **Java常用类**:如String、Integer等,提供了丰富的API供开发者使用。 - **接口**:一种只包含抽象方法的特殊类,用于定义行为的标准。 - **抽象类**:不能被实例化的类,通常用于定义一组相关类的公共行为。 ##...

    java开始面试的第63天.doc

    静态SQL在编译时确定,性能高且Oracle使用缓存游标优化。动态SQL则在运行时编译,适应性强,但可能导致性能下降,尤其是不使用绑定变量时。 **异常分类** 在PL/SQL中,异常分为Oracle预定义异常(如`NO_DATA_FOUND...

    最新Java面试宝典pdf版

    1、一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制? 7 2、Java有没有goto? 7 3、说说&和&&的区别。 8 4、在JAVA中如何跳出当前的多重嵌套循环? 8 5、switch语句能否作用在byte上,能否作用在...

    Java面试宝典2012版

    1、一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制? 7 2、Java有没有goto? 7 3、说说&和&&的区别。 8 4、在JAVA中如何跳出当前的多重嵌套循环? 8 5、switch语句能否作用在byte上,能否作用...

    Java面试宝典-经典

    1、一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制? 7 2、Java有没有goto? 7 3、说说&和&&的区别。 8 4、在JAVA中如何跳出当前的多重嵌套循环? 8 5、switch语句能否作用在byte上,能否作用在...

    java面试题大全(2012版)

    1、一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制? 7 2、Java有没有goto? 7 3、说说&和&&的区别。 8 4、在JAVA中如何跳出当前的多重嵌套循环? 8 5、switch语句能否作用在byte上,能否作用在...

    java面试宝典2012

    1、一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制? 8 2、Java有没有goto? 8 3、说说&和&&的区别。 8 4、在JAVA中如何跳出当前的多重嵌套循环? 8 5、switch语句能否作用在byte上,能否作用在...

Global site tag (gtag.js) - Google Analytics