關於String的intern方法

    @Test
    public void testfdk2(){
        String a1=new String ("aaa1");//同時會生成堆中的對象 以及常量池中1的對象,但是此時a1是指向堆中的對象的
        String x=a1.intern();//"aaa1" 常量池中的已經存在,之後返回引用,不會將a1當做"aaa1"的引用,a1指向的一樣是String對象
        String a2="aaa1";
        System.out.println(a2==a1);  //false  此時a1指向的是對象的地址
        System.out.println(x==a2);//true x 是"aaa1"的引用
    }

    @Test
    public void testfdk3(){
        String string=new String("he")+new String("llo");//  常量池中+ 堆中 + s3指向的堆中的對象(注此時常量池不會生成"hello")
        String x=string.intern();					//   在常量池中找,沒有“hello”這個常量對象,所以生成常量引用,和堆中那個對象的地址相同
        String str2="hello";			
        System.out.println(string==str2);//false
        System.out.println(x==str2);//true
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章