String字符串

来源:互联网 发布:淘宝没有鼠尾草籽 编辑:程序博客网 时间:2024/06/04 18:27
public class ObjectTest{        public static void main(String[] args)        {                Object o1 = new Object();                Object o2 = new Object();                System.out.println(o1 == o2);//生成新的对象,对象引用的地址不同                System.out.println("………………one……………………");                String s1 = new String("aaa");                String s2 = new String("aaa");                System.out.println(s1 == s2);                System.out.println("………………two……………………");//生成新的对象,对象引用的地址不同                String ss1 =  "bbb";                String ss2 =  "bbb";                System.out.println(ss1 == ss2);                System.out.println("………………three……………………");                String str1 = "ccc";                String stO = new String("ccc");                System.out.println(str1 == stO);                System.out.println("………………four……………………");                String helloWorld = "helloWorld";                String hello = "hello";                String world = "World";                System.out.println(helloWorld == hello + world);                System.out.println("……………………five………………………………");                System.out.println(helloWorld == "hello"+"World");                System.out.println("………………six……………………");                System.out.println(helloWorld == (hello + world).intern());        }}


运行的结果

false………………one……………………false………………two……………………true………………three……………………false………………four……………………false……………………five………………………………true………………six……………………true

解析:

1.object在堆中分别创建对象,引用地址不一样

2.String创建对象时:i)首先在String pool查找有没有”aaa“这个字符串对象,如果有,则不需要再String pool中创建”aaa“,直接在堆(heap)中创建”aaa“字符串对象,并把堆中字符串对象的地址返回;ii)如果String pool中没有”aaa“字符串对象,在String pool中创建”aaa“对象,并在堆(heap)中创建”aaa“的字符串对象,并把堆中字符串对象的地址返回

3.首先在String pool查找有没有”aaa“对象,有则返回其地址,没有则创建该对象,并将其引用的地址返回

4.一个指向String pool一个指向Heap

5和6得出的结果不一样

6.参考String.intern()方法(返回String pool中的引用地址)

intern

public String intern()
返回字符串对象的规范化表示形式。

一个初始为空的字符串池,它由类 String 私有地维护。

当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(用 equals(Object) 方法确定),则返回池中的字符串。否则,将此String 对象添加到池中,并返回此 String 对象的引用。

它遵循以下规则:对于任意两个字符串 st,当且仅当 s.equals(t)true 时,s.intern() == t.intern() 才为 true


 

原创粉丝点击