有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (5) 个答案

  1. # 1 楼答案

    Java尽可能尝试将字符串“共享”到安全空间

    String txt1="Hello";
    String txt2="Hello";
    

    是对同一对象的两个引用(“Hello”)

    String txt1=new String("Hello");
    String txt2=new String("Hello");
    

    是对两个不同实例的两个引用,每个引用都由副本初始化

    如果比较字符串,请始终使用“equals()”,否则结果很难预测

  2. # 2 楼答案

    这样做

    String txt1="Hello";
    String txt2="Hello";
    System.out.println(txt1.hashCode());
    System.out.println(txt2.hashCode());
    System.out.println((boolean)txt1==txt2);
    
    
    String txt1=new String("Hello");
    String txt2=new String("Hello");
    System.out.println(txt1.hashCode());
    System.out.println(txt2.hashCode());
    System.out.println((boolean)txt1==txt2);
    

    您可以了解java如何在内部处理

  3. # 3 楼答案

    字符串是对象==比较对象引用,而不是字符串的内容。为此,请使用String#equals方法

    在第一个示例中,txt1txt2是指向同一String对象的两个变量。所以他们彼此==

    在第二个示例中,txt1txt2指向两个不同的String对象(它们具有相同的字符序列),因此它们彼此不==


    另外:写new String("string literal")几乎没有任何意义。如果你不知道一个非常非常好的理由去做这件事,那就不要这样做。只有几个非常非常非常非常不寻常的情况下,你可能会这样做,这与与与低级事物的互动有关。不是在普通的可移植Java代码中

    偶尔有使用new String(String)的理由(不是字符串文本,而是从其他地方获得的实例,如substring)。有关这方面的更多信息,请参见this article(谢谢Rp-

  4. # 4 楼答案

    如果要比较引用,请使用==运算符

    如果要比较两个字符串的内容,请使用equals方法

  5. # 5 楼答案

    ==运算符将检查引用是否相等,即,如果两个参数String是同一实例,则将返回true

    每当类中出现String文本(例如"Hello")时,String实例被interned(某种程度上存储在内部缓存中,以便可以重用)

    在做了String txt1="Hello"之后,txt1将是与实习生String非常相同的参考。所以

    String txt1="Hello";
    String txt2="Hello";
    

    结果txt1txt2是同一个实例,即,被拘留的实例

    当您执行String txt1=new String("Hello")时,它将调用String构造函数,并将插入的实例作为参数(类似于复制构造函数)。因此,txt1将是一个新的String实例,其值与内部实例相同,==操作符将返回false

    关于这个主题的更多信息可以在JLS的3.10.5. String Literals部分找到

    A string literal is a reference to an instance of class String (§4.3.1, §4.3.3).

    Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

    以下问题的答案解释了When are Java Strings interned?。下面的链接详细介绍了这个主题:String Equality and Interning

    作为旁注,请记住使用equals()以便根据其内容执行字符串比较