字符串懶加載的證明

字符串是懶加載的,運行的時候相同的字符串會在串池中保存,怎麼去證明這件事呢?其實方法很簡單,我們利用Idea中的調試就可以看到內存中對象的狀態。
準備代碼:

import com.sun.tools.attach.AttachNotSupportedException;
import sun.tools.attach.HotSpotVirtualMachine;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

/**
 * 字符串延遲加載的證明
 */
public class StringLazyLoad {
    public static void main(String[] args)  {

        System.out.println("h");

        System.out.println("a");
        System.out.println("b");
        for(int i=0;i<200;i++){
            System.out.println("a");
        }

        System.out.println("c");
        System.out.println("d");
        System.out.println("e");
        System.out.println("f");

        for(int i=0;i<200;i++){
            System.out.println("a"+i);
        }
        System.out.println("g");
    }
}

直接斷點查看字符串的個數,到18行的時候是1227
在這裏插入圖片描述
我們執行到b,字符串的個數是1228,說明是在執行的時候纔會加載實例
在這裏插入圖片描述
我們執行到24行,發現字符串實例的個數1229,並沒有因爲循環的次數增加200個實例
在這裏插入圖片描述
說明我們的字符串對象不是來一次新建一次的。

發佈了39 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章