zoukankan      html  css  js  c++  java
  • 结合字符串常量池/String.intern()/String Table来谈一下你对java中String的理解

    1、字符串常量池

    每创建一个字符串常量,JVM会首先检查字符串常量池,如果字符串已经在常量池中存在,那么就返回常量池中的实例引用。如果字符串不在池中,就会实例化一个字符串放到字符串池中。常量池提高了JVM性能和内存开销

    2、用new 的方式创建字符串

    new方式创建字符串,会先检查常量池中是否有相同值的字符串。如果有,则拷贝一份到堆中,然后返回堆中的地址。如果没有,则在堆中创建一份,然后返回堆中的地址。

    3、String Table

    String Table存放的是string的cache table,用于存放字符串常量的引用的表,避免产生新的string的开销。它的结构类似于我们常用的hashtable

    4、String.intern()

    intern用来返回常量池中的某字符串,如果常量池中已经存在该字符串,则直接返回常量池中该对象的引用。否则,在常量池中加入该对象,然后 返回引用。

    package myProject;
    
    public class StringTest {
        public static void main(String[] args) {
            
            String s1="hello";
            String s2="hello";
            String s3 =new String("hello");
            System.out.println(s1==s2);//true
            System.out.println(s2==s3);//false
            String s4=s3.intern();
            System.out.println(s2==s4);//true
        }    
    }
  • 相关阅读:
    apex Error : Given no hashes to check 137 links for project 'pip': discarding no candidates
    源码编译pytorch-1.2.0
    proxychains
    git简单教程
    caffe ssd + cuda9.0
    ros+pcl error recoder
    硬盘挂载
    opencv3.4.1+ubuntu18.04+anaconda 源码编译
    从RocksDBStateBackend讲述Flink的State机制
    由Rocksdb状态后端引出的Tree的应用
  • 原文地址:https://www.cnblogs.com/BonnieWss/p/9267088.html
Copyright © 2011-2022 走看看