1. 程式人生 > 遊戲 >由於無法預見的問題 《狙擊手:幽靈戰士契約2》PS5版延期

由於無法預見的問題 《狙擊手:幽靈戰士契約2》PS5版延期

String類

String類

首先對於String型別,我們先檢視它的原始碼:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
 
    /** Cache the hash code for the string */
    private
int hash; // Default to 0 /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -6849794470754667710L;

由此我們可以知道,String型別內部維護的char[]陣列,且其是由final修飾的,可知一旦建立就不能在修改。

1.在建立字串S後,Java執行時會拿著這個S字串在字串常量池中查詢是否存在內容相同的字串物件,如果不存在,則在池中建立一個字串S,否則不會建立物件,也不會在池中新增。

2.使用new關鍵建立物件,那麼肯定會在堆疊建立一個新的物件,String也是一樣的。
3.使用直接指定或者使用純字串拼接來建立String物件,則僅僅會檢查String池中的字串,池中沒有就建立一個,如果存在,就不需要建立新的,但是絕對不會在堆疊區再去建立物件。
4.使用包含變數的表示式來建立String物件時,則不僅會檢查並維護字串常量池,而且還會在堆疊區建立一個新的String物件

字串拼接

1.利用"+"

public class TestDemo {
    public static void main(String[] args) {
        String str1=
"hello "; String str2="world"; String str3=str1+str2; System.out.println(str3); } }

2.利用concat

public class TestDemo {
    public static void main(String[] args) {
        String str1="hello ";
        String str2="world";
        String str3=str1.concat(str2);
        System.out.println(str3);
    }
}

3.利用StringBuffer

public class TestDemo {
    public static void main(String[] args) {
        StringBuffer str3=new StringBuffer("hello");
        str3.append(" ").append("world");
        System.out.println(str3);
    }
}

總結:若拼接三個以上的字串,為避免臨時字串的產生可以選擇StringBuffer,若拼接三個以上的字串,只選擇一行語句程式碼,選擇"+",效率最高,選擇concat。

字串比較

在比較字串內容是否相同時,要使用equals比較,不能使用"=="比較。

public class TestDemo {
    public static void main(String[] args) {
        String str1="hello";
        String str2="hello";
        System.out.println(str1==str2);
        System.out.println(str1.equals(str2));
    }
}

輸出結果:
在這裡插入圖片描述
因為在建立str2時,會再字串常量池中查詢是否有和str2內容相同的字串,因為在字串常量池中已經建立了str1=hello,故str1和str2所佔記憶體地址也是相同的,內容也相同,故而輸出均為true。

public class TestDemo {
    public static void main(String[] args) {
        String str1="hello";
        String str2=new String("hello");
        System.out.println(str1==str2);
        System.out.println(str1.equals(str2));

    }

}

輸出結果:
在這裡插入圖片描述
此時,str2則是被new出來了,則需要為其開闢新的記憶體空間,故而第一個輸出為false,equals比較的是字串的內容。
因此,在比較字串內容時應該使用的是equals。