博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
String特性之 “字符串驻留池”
阅读量:2062 次
发布时间:2019-04-29

本文共 1075 字,大约阅读时间需要 3 分钟。

再说  String
1. 字符串驻留池,就是一块与堆区并行的存放字符串对象的内存区,JVM的驻留池机制规定: 
在池中创建一个String对象,第二行会先在池中寻找是否有值与"abc"相同的String对象,如果有,就直接引用,没有这在池中新建String对象
知识补充:
1. JVM 为了提高性能,会将形式例如:String  str = "我是字符串"   和   “我也是字符串” 的 字符串存放在一个名叫:字符串驻留池的内存块中。 
2. 通过new 所产生的对象 是在堆中存放的。
3 .    " == "  判断两个字符串对象时 : 当两个字符串对象完全相同时 返回true , 当内容不同或者 不是同一个对象时返回false  
举例子说明:
public class String_Test
{
    public static void main(String[] args)
    {
        String str1 = new String("字符串1");    // str1对象存放在堆里
        String str2 = "字符串1" ;               //  str2 对象是存放在驻留池
 
        String str3 = new String ("字符串3");    
        str3 = str3.intern();                 // 通过intern把new创建的对象str3放入驻留池
        String str4 = "字符串3" ;             //  JVM会将str4 指向str3在驻留池创建的对象        
        if(str1 == str2)   // 很明显 str1  和  str2 虽然是相同内容,但是不是同一对象。                   
        {
            System.out.println("str1 == str2");
        }else {
            System.out.println("str1 != str2");
        }
 
        if(str3 == str4)   // JVM的字符串驻留机制    str3  str4 是同一个对象
        {
            System.out.println("str3 == str4");        
        }else {
            System.out.println("str3 != str4");
        }
    }
}
 
结果:
str1 != str2       //   str1 str2 引用的对象不是同一个对象。
str3 == str4                 //
 表明使用驻留后的str3 str4 引用的对象是同一个对象。
 
拓展视野:
一个面试题 :  
 String  str = new String  ("King");    问: 这句话创建了几个对象?
 
答案: 2个    一个由new 在堆区产生  另一个在 驻留池中产生

转载地址:http://fgalf.baihongyu.com/

你可能感兴趣的文章
Leetcode C++《热题 Hot 100-15》437.路径总和III
查看>>
Leetcode C++《热题 Hot 100-17》461.汉明距离
查看>>
Leetcode C++《热题 Hot 100-18》538.把二叉搜索树转换为累加树
查看>>
Leetcode C++《热题 Hot 100-19》543.二叉树的直径
查看>>
Leetcode C++《热题 Hot 100-21》581.最短无序连续子数组
查看>>
Leetcode C++《热题 Hot 100-22》2.两数相加
查看>>
Leetcode C++《热题 Hot 100-23》3.无重复字符的最长子串
查看>>
Leetcode C++《热题 Hot 100-24》5.最长回文子串
查看>>
Leetcode C++《热题 Hot 100-26》15.三数之和
查看>>
Leetcode C++《热题 Hot 100-27》17.电话号码的字母组合
查看>>
Leetcode C++《热题 Hot 100-28》19.删除链表的倒数第N个节点
查看>>
Leetcode C++《热题 Hot 100-29》22.括号生成
查看>>
Leetcode C++《热题 Hot 100-40》64.最小路径和
查看>>
Leetcode C++《热题 Hot 100-41》75.颜色分类
查看>>
Leetcode C++《热题 Hot 100-42》78.子集
查看>>
Leetcode C++《热题 Hot 100-43》94.二叉树的中序遍历
查看>>
Leetcode C++ 《第175场周赛-1 》5332.检查整数及其两倍数是否存在
查看>>
Leetcode C++ 《第175场周赛-2 》5333.制造字母异位词的最小步骤数
查看>>
Leetcode C++ 《第175场周赛-3》1348. 推文计数
查看>>
Leetcode C++《热题 Hot 100-44》102.二叉树的层次遍历
查看>>