Java 複習 —— String


一、String的實例過程

    Java字符串的維護就是一個享元模式的具體體現,咱們知道String的實例有兩種方式分別是:java

String str =  "hello world";
String str2 = new String("hello world");

    其中前者字面量的方式具體流程是這樣的:首先查找 String Pool(棧)中是否有「hello world」,若是不存在,那會在String Pool中建立一個「hello world」,同時將這個對象的引用返回給str;若是String Pool中存在,那麼直接獲取String Pool中的值返回;設計模式

    後者new一個的對象的具體流程是這樣的:首先查找 String Pool中是否有「hello world」,若是不存在,那麼一樣在String Pool中建立一個,而後去堆(Heap)中建立一個「hello world」對象,而且把堆中的引用返回給str2;若是String Pool中存在了這個對象,那麼,跳過String Pool中建立,而是直接在堆中去建立一個「hello world」而後把引用返回。數組

    經過以上就會明白:性能

爲何ui

"hello world" == "hello world" 爲 true ;

可是 this

new String("hello world") == new String("hello wrold") 爲 false;

同時 spa

"hello world" == new String("hello world") 也爲false;

    另外,String Pool 就是一個字符串的享元工廠,字面量的方式就是一個享元工廠模式。你們都知道StringBuffer的性能要好過 String,StringBuilder的性能要好過StringBuffer,但是爲何還要用String呢?緣由就在這裏,他們說的性能是字符串 修改的時候,而真正字符的基本操做,以及字符串從系統中獲取的時候,String是最快的,維護的對象也最少。設計


二、String的相等判斷

    String 重寫了equals方法,Object的equals方法是直接比較兩個對象的地址,因此使用在字符串上比較意義不是很大,想要判斷兩個字符串的是否相同,咱們應該這樣判斷,採用重寫的equals方法。具體代碼以下:code

     public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = offset;
        int j = anotherString.offset;
        while (n-- != 0) {
            if (v1[i++] != v2[j++])
            return false;
        }
        return true;
        }
    }
    return false;
    }

三、String 其餘注意事項

1)、字符串沒有屬性暴露,內部有屬性通常是私有並且final類型的;好比offset、count、value;對象

2)、字符串重寫了equals方法,那麼也必定後重寫了hashcode方法;

3)、字符串不能被繼承是由於他是一個final類型的類;

4)、字符串內容不能更改是由於內部使用一個final類型的char數組存儲,因此不能改變;

5)、字符串的優點在於他的速度,由於他的設計是一種享元設計模式。

相關文章
相關標籤/搜索