【问题标题】:Java: Beginner question regarding StringsJava:关于字符串的初学者问题
【发布时间】:2019-09-01 16:34:57
【问题描述】:

在Java中创建String时,这两者有什么区别:

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

String test = "foo";

什么时候需要使用关键字new?还是这两个基本相同,都创建了一个新的String对象?

【问题讨论】:

  • 字符串测试 = 新字符串(); -> 创建一个新的 String 实例,您将永远不会再使用它,因为您将变量 test 重新分配给“foo”,这意味着分配 '= new String()' 是没有意义的
  • @ernest_k 这并不是该线程的真正副本。他在他的一个示例中进行了两次单独的分配,而不是使用 String 的重载构造函数进行分配
  • @Stultuske 对。我已经重新打开了。
  • 如果您是初学者,请不要先查看 stackoverflow。查看 Oracle 的 Java 教程:docs.oracle.com/javase/tutorial/java/data/strings.html
  • 这样的问题总能磨练你的基础:)

标签: java string object


【解决方案1】:

在第一个 sn-p 中,您创建一个新的空字符串,然后立即用字符串文字覆盖它。您创建的新字符串会丢失,最终会被垃圾回收。
创建它是没有意义的,你应该只使用第二个sn-p。

【讨论】:

    【解决方案2】:

    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));
       }
    }
    
    

    在大多数情况下,您不需要创建字符串的新对象,因为在使用例如字符串时您没有静态值。 HashMaps 或类似的东西。

    因此,仅在真正需要时使用new String 创建新字符串。主要使用String yourString = "...";

    【讨论】:

      【解决方案3】:

      这是一个示例程序,可帮助您了解字符串在 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 中的字符串是不可变的。

      您可以在What is Java String interning?这个问题上进一步阅读

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-12
        • 2018-01-08
        • 1970-01-01
        • 2021-03-04
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        相关资源
        最近更新 更多