java - Java 中 Wrapper 类的行为

标签 java wrapper

<分区>

Possible Duplicate:
Why does 128==128 return false but 127==127 return true in this code?

下面这段Java代码返回true

Integer i1=1;
Integer i2=1;
System.out.println(i1==i2);

那么我们在 Java 中有字符串常量池的概念,我们在 Java 中的包装类的情况下是否也有类似的概念?

最佳答案

Java 也有用于 -128 到 127 之间的小整数的整数池,因此它对整数的行为与字符串常量池相似

您将在Integer 类中找到以下代码

private static class IntegerCache {
    static final int high;
    static final Integer cache[];

    static {
        final int low = -128;

        // high value may be configured by property
        int h = 127;
        if (integerCacheHighPropValue != null) {
            // Use Long.decode here to avoid invoking methods that
            // require Integer's autoboxing cache to be initialized
            int i = Long.decode(integerCacheHighPropValue).intValue();
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - -low);
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

    private IntegerCache() {}
}

也如以下毒药回答所述:

Chapter 5. Conversions and Promotions

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

关于java - Java 中 Wrapper 类的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12306853/

相关文章:

java - 在 Netbeans 中设置 Apache POI API,

c++ - 包装模板函数和<未解析的重载函数类型

java - 实例化接口(interface)对象 - 如何?

PHP:标准输出与 php://STDOUT

java - 创建类似 ArrayList 的类时出现 NullPointerException

java - 如何为所有 JUnit 测试创建对象?

Java/Android 正则表达式问题

java - 在 Java 中模拟文件

php - 如何检查 php 是否为 ://input is set?

java - JNI : How to handle the creation/removal of wrapped C++ object