是是是22222222 2015-03-22 05:52 采纳率: 0%
浏览 1778

请教大神们一个java包装类的问题

请教大神们一个java包装类的问题,

String str = "abc";
String str2 = "abc";
System.out.println(str == str2);

Integer i = Integer.valueOf(1);
Integer i2 = Integer.valueOf(1);
System.out.println(i ==i2);

我知道str和str2是存放在字符串常量池中的,所以他们是相等的,但是i和i2相等能说明这两个是同一个对象吗? 我认为i和i2相等是因为 比较它们的时候自动拆箱,按照基本数据类型来比较了, 另外关于基本类型比如int,也是类似于String常量池那样存储的吗? 就是说我有两个int值如果相等的话,它们在内存中是否就是相同的呢?

这个问题是在看 think in java 第17章 深入理解容器 时想到的,书中在将填充容器时写了一个填充Integer的自定义的List,然后说这是享元,我有点想不明白,求大神们指点呀!下面是书中的代码:

 public class CountingIntegerList
extends AbstractList<Integer> {

private int size;
public CountingIntegerList(int size) {
this.size = size < 0 ? 0 : size;
}
public Integer get(int index) {
//我这里不太明白,难道每次按照相同index取出的Integer都是同一个对象???
return Integer.valueOf(index);
}
public int size() { return size; }
public static void main(String[] args) {
System.out.println(new CountingIntegerList(30));
}
}
  • 写回答

3条回答 默认 最新

  • 0808xyj 2015-03-22 06:41
    关注

    的确 为一个对象,范围是-128 至 127

     static final int low = -128;
            static final int high;
            static final Integer cache[];
    
            static {
                // high value may be configured by property
                int h = 127;
                String integerCacheHighPropValue =
                    sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
                if (integerCacheHighPropValue != null) {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                }
                high = h;
    
                cache = new Integer[(high - low) + 1];
                int j = low;
                for(int k = 0; k < cache.length; k++)
                    cache[k] = new Integer(j++);
            }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?