美文网首页
聊聊Java常量池

聊聊Java常量池

作者: 方学顺 | 来源:发表于2018-08-12 04:55 被阅读0次

从老生常谈的包装类型“==” 和 “equals” 说起

最近在刷leetcode题时,又学到了很多之前没有注意到的点,随便写写,想到哪,写到哪吧。

  • 请看如下代码:
    public static void main(String[] args) {
        //这里改成Integer integerA = new Integer(12)会对最终结果有影响,后面会说明
        Integer integerA = 12;
        Integer integerB = 12;
        System.out.println("integerA="+integerA+",integerB="+integerB);
        if(integerA == integerB){
            System.out.println("integerA == integerB");
        }else {
            System.out.println("integerA != integerB");
        }

        if(integerA.equals(integerB)){
            System.out.println("integerA equals integerB");
        }else {
            System.out.println("integerA not equals integerB");
        }

    }
  • 上述代码输出为:
integerA=12,integerB=12
integerA == integerB
integerA equals integerB
  • 修改变量A、B的值为integerA=128,integerB=128之后,输出为:
integerA=128,integerB=128
integerA != integerB
integerA equals integerB
  • 此时integerA != integerB
  • equals方法:这里Integer 包装类重写了equals方法,比较的是内置基础类型的值,同一个值是同一地址。可以这样理解,在编译时,IntegerA 和 IntegerB是引用类型的对象,他们两个有自己的地址,其中Integer对象中的value变量的地址是同一个。
    //Integer.java
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
    
        /**
     * Returns the value of this {@code Integer} as an
     * {@code int}.
     */
    public int intValue() {
        return value;
    }
  • “==”比较的是引用或者说地址是否相等(8种基本类型可以理解为直接比较的值)正常情况下,IntegerA 和 IntegerB作为一个引用 类型的对象调用“==”比较,都应该不同,而这里变量等于12时,,IntegerA 和 IntegerB是同一个引用,正是因为java常量池。
  • 关于jvm内存可以参考:JVM内存模型。注意jdk1.7中的常量池移到了堆内存中,同时在jdk1.8中移除整个永久代,对应的是元空间(Metaspace)区域的引进。Oracle jdk1.7说明,RFE 6962931

何为常量池?

  • 通俗的讲,即为常量共享的一种方案。可以参考这篇文章,讲的很详细。Java常量池理解与总结
  • 5种包装类(Byte,Short,Integer,Character,Long) ,内存中只缓存-128 到 127范围内的数据,其中Byte类型全部进行了缓存。这也是为什么当时我们初始化的值比128小时,引用都是用的同一个的原因。如果我们初始化时使用new Integer(12),则不会相同。直接上代码:
Integer.java
/**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} 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.
     *
     * This method will always cache values in the range -128 to 127,
     (划重点,内存中只缓存-128 to 127范围内的数据)
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    
    
    Byte.java
    /**
     * Returns a {@code Byte} instance representing the specified
     * {@code byte} value.
     * If a new {@code Byte} 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 since
     * all byte values are cached.
     *(全部 byte 值已经缓存)
     *
     * @param  b a byte value.
     * @return a {@code Byte} instance representing {@code b}.
     * @since  1.5
     */
    public static Byte valueOf(byte b) {
        final int offset = 128;
        //这里加偏移量是因为byte对应的整数值和缓存索引值并非相等
        return ByteCache.cache[(int)b + offset];
    }
    
   
    /**
     *  Byte.java中的内部类
     */
        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));
        }
    }

知道了这些有什么用

  • 享元模式Flyweight Design Pattern in Java
  • 享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,减少对象数量从而改善应用所需的对象结构的方式。实现方式一般是通过HashMap完成。java常量池的设计初中也是为了减少内存占用,同时保证访问安全。继承Number的包装类常量池存储使用数组,String使用继承自HashTable的SStringTable:
op StringTable::basic_add(int index_arg, Handle string, jchar* name,
                           int len, unsigned int hashValue_arg, TRAPS) {

  // ...

  HashtableEntry<oop, mtSymbol>* entry = new_entry(hashValue, string()); // 新建
  add_entry(index, entry);    // 添加
  return string();
}
  • 说到底,设计模式是为了解决实际问题,而不是炫技,从问题出发,找出解决问题的方案,如果该方案是通用的,也就成了设计模式了。
  • 在查资料的过程中,好多人的文章已经过时了,有的说的不准确甚至错误的。甄别的过程,也是蛮花力气的。要养成独立思考的习惯,有矛盾的,以官方资料为准。

相关文章

  • 聊聊Java常量池

    从老生常谈的包装类型“==” 和 “equals” 说起 最近在刷leetcode题时,又学到了很多之前没有注意到...

  • java基础类型、String类理解、版本对比、1.8新特性

    1、java基本数据类型及长度 2、jvm的常量池: JVM常量池浅析Java常量池理解与总结 Java中的常量池...

  • 细说Java常量池

      Java中的常量池有:class常量池、运行时常量池、String常量池。 为什么要使用常量池?   避免频繁...

  • java__常量池

    java的常量池分为两种型态:静态常量池和运行常量池 静态常量池: 即class文件中的常量池,这种常量池主要用于...

  • 常量池、运行时常量池、字符串常量池

    常量池、运行时常量池、字符串常量池 Java里包含各种常量池,经常傻傻分不清楚,下面就简单梳理下Java中的池们。...

  • JVM(六)JVM常量池

    1.常量池类型 Java中的常量池分为三种: 类文件常量池(静态常量池)(The Constant Pool)运行...

  • Java 内存—常量池

    Java中的常量池分为两种型态: 静态常量池 运行时常量池 静态常量池 所谓静态常量池是指class文件中的常量池...

  • 你对常量池够了解吗

    在 java 中,常量池分为以下三种: class 常量池 字符串常量池 运行时常量池 一、class 常量池 1...

  • 常量池

    Java中的常量池,实际上分为两种形态:静态常量池和运行时常量池。 静态常量池 : *.class文件中的常量池,...

  • Java中的常量池

    Java中的常量池分为三类:字符串常量池、class常量池、运行时常量池 字符串常量池 从1.7及其之后,字符串常...

网友评论

      本文标题:聊聊Java常量池

      本文链接:https://www.haomeiwen.com/subject/spwjbftx.html