zoukankan      html  css  js  c++  java
  • 转java之基础 equals和==比较

    equals和==比较

    今年工作原因开始.net转java,记录一些平常学习和工作中的知识

    对于 Integer var = ? 在-128 至 127 范围内的赋值,Integer 对象是在 IntegerCache.cache 产生,会复用已有对象,这个区间内的 Integer 值可以直接使用==进行 判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象,这是一个大坑, 推荐使用 equals 方法进行判断(如果Integer对象的数值在上述范围之外,会比较Integer对象,此时如果再用“==”会比较出两个对象地址不同。)

     

    看源码,这里比较是否在缓存值之内(-128到127),如果存在就取缓存的中值,如果不是就new一个对象,缓存里的是为int类型,---包装类和基本类型的区别

    public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
    }
    private static class IntegerCache {
    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) {
    try {
    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);
    } catch( NumberFormatException nfe) {
    // If the property cannot be parsed into an int, ignore it.
    }
    }
    high = h;

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

    // range [-128, 127] must be interned (JLS7 5.1.7)
    assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
    }
  • 相关阅读:
    MongoDB权限验证
    【大型网站开发系列第一篇】——网站结构层次
    php5.4的htmlspecialchars处理中文
    将session值字符串重新生成session
    php支持短标签
    solr suggest+autocomplete实现自动提示
    linux命令
    【技术】【转】字节序问题大端法小端法
    eeePC(易PC)变态测试!(上)
    "挑iPod不问价"就是不懂“性价比”?
  • 原文地址:https://www.cnblogs.com/xwx20160804/p/11719602.html
Copyright © 2011-2022 走看看