簡體   English   中英

Java:關於字符串的初學者問題

[英]Java: Beginner question regarding Strings

在Java中創建String時,這兩者之間有什么區別:

String test = new String();
test = "foo";

String test = "foo";

我什么時候需要使用關鍵字new? 或者這兩個基本相同,它們都創建一個新的String對象?

在第一個片段中,您創建一個新的空字符串,然后立即用字符串文字覆蓋它。 您創建的新字符串將丟失,最終將被垃圾回收。
創建它是沒有意義的,你應該只使用第二個片段。

new String()將使用自己的標識哈希碼創建對象字符串的新實例。 創建類似String string = "myString"; Java將嘗試通過搜索已創建的字符串來重用該字符串,以獲得該字符串。 如果找到,它將返回該字符串的相同標識哈希碼。 這將導致,如果您創建例如字符串的標識哈希碼,您將獲得相同的值。

例:

public class Stringtest {
   public static void main(String[] args) {
      final String s = "myString";
      final String s2 = "myString";
      final String otherS = new String("myString");

      //S and s2 have the same values
      System.out.println("s: " + System.identityHashCode(s));
      System.out.println("s2: " + System.identityHashCode(s2));

      //The varaible otherS gets a new identity hash code
      System.out.println("otherS: " + System.identityHashCode(otherS));
   }
}

在大多數情況下,您不需要創建字符串的新對象,因為在處理HashMap或類似事物時您沒有靜態值。

因此,只有在真正需要時才使用new String創建新的字符串。 大多使用String yourString = "...";

這是一個示例程序,可幫助您了解字符串在Java中的工作方式。

import java.util.Objects;

public class TestStrings {

    public static void main(String[] args) {
        String test = new String();
        System.out.println("For var test value is '"+ test+ "' and object identity is "+ System.identityHashCode(test));
        test = "foo";
        System.out.println("For var test after reassignment value is '"+ test+ "' and object identity is "+ System.identityHashCode(test));
        String test2 = "foo";
        System.out.println("For var test2 value is '"+ test2+ "' and object identity is "+ System.identityHashCode(test2));
        String test3 = new String("foo");

        System.out.println("For var test3 value is '"+ test3+ "' and object identity is "+ System.identityHashCode(test3));
    }
}

運行此命令以查看為變量testtest2test3打印的標識哈希代碼會發生什么。

基本上,Java會嘗試優化字符串在創建為文字時的創建方式。 Java嘗試維護字符串池,如果再次使用相同的文字,它將使用此字符串池中的相同對象。 這可以做到,因為java中的字符串是不可變的。

你可以在這個問題上進一步閱讀什么是Java String interning?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM