java常量池

来源:互联网 发布:linux bash脚本 编辑:程序博客网 时间:2024/04/30 00:06

Java的8种基本类型(Byte, Short, Integer, Long, Character, Boolean, Float, Double), 除Float和Double以外, 其它六种都实现了常量池, 但是它们只在大于等于-128并且小于等于127时才使用常量池。

由如下例子可以看出:

 

[java] view plaincopy
  1. public static void main(String[] args) {  
  2.     Integer a = 127;  
  3.     Integer b = 127;  
  4.     System.out.println("等于127:");  
  5.     System.out.println(a == b);  
  6.     System.out.println("*****************");  
  7.     a = 128;  
  8.     b = 128;  
  9.     System.out.println("等于128:");  
  10.     System.out.println(a == b);  
  11.     System.out.println("*****************");  
  12.     a = -128;  
  13.     b = -128;  
  14.     System.out.println("等于-128:");  
  15.     System.out.println(a == b);  
  16.     System.out.println("*****************");  
  17.     a = -129;  
  18.     b = -129;  
  19.     System.out.println("等于-129:");  
  20.     System.out.println(a == b);  
  21.     System.out.println("*****************");  
  22.     // 测试Boolean  
  23.     System.out.println("测试Boolean");  
  24.     Boolean c = true;  
  25.     Boolean d = true;  
  26.     System.out.println(c == d);  
  27.     d = new Boolean(true);  
  28.     System.out.println(c == d);  
  29. }  
 

 

结果如下:

等于127:
true
*****************
等于128:
false
*****************
等于-128:
true
*****************
等于-129:
false
*****************
测试Boolean
true
false

当我们给Integer赋值时,实际上调用了Integer.valueOf(int)方法,查看源码,其实现如下:

 

[java] view plaincopy
  1. public static Integer valueOf(int i) {  
  2.     if(i >= -128 && i <= IntegerCache.high)  
  3.         return IntegerCache.cache[i + 128];  
  4.     else  
  5.         return new Integer(i);  
  6. }  
 

 

而IntegerCache实现如下:

 

[java] view plaincopy
  1. private static class IntegerCache {  
  2.     static final int high;  
  3.     static final Integer cache[];  
  4.     static {  
  5.         final int low = -128;  
  6.         // high value may be configured by property  
  7.         int h = 127;  
  8.         if (integerCacheHighPropValue != null) {  
  9.             // Use Long.decode here to avoid invoking methods that  
  10.             // require Integer's autoboxing cache to be initialized  
  11.             int i = Long.decode(integerCacheHighPropValue).intValue();  
  12.             i = Math.max(i, 127);  
  13.             // Maximum array size is Integer.MAX_VALUE  
  14.             h = Math.min(i, Integer.MAX_VALUE - -low);  
  15.         }  
  16.         high = h;  
  17.         cache = new Integer[(high - low) + 1];  
  18.         int j = low;  
  19.         for(int k = 0; k < cache.length; k++)  
  20.             cache[k] = new Integer(j++);  
  21.     }  
  22.     private IntegerCache() {}  
  23. }  
 

 

注意cache数组是静态的。