gpt4 book ai didi

java - .equals() 创建类构造函数并比较简单字符串

转载 作者:行者123 更新时间:2023-12-01 18:00:49 24 4
gpt4 key购买 nike

我在java中用.equals()编写了一个程序,当我在youtube上看到一些在线视频并搜索了这个东西但没有得到正确的解释时,我遇到了一些概念问题。所以大家帮我解决这个问题。

谢谢。

package Practice;

public class StringManipulation11 {

StringManipulation11(String s) {
}

public static void main(String[] args) {

String s = "Good";
String s1 = "Good";
String s2 = "Morning";

String t = new String("Good");
String t1 = new String("Good");
String t2 = new String("Morning");

StringManipulation11 sm = new StringManipulation11("Good");
StringManipulation11 sm1 = new StringManipulation11("Good");

System.out.println(s.equals(s1));// true because check content
System.out.println(s.equals(s2));// false content not match

System.out.println(t.equals(t1));// true because check content
System.out.println(s.equals(t));// true because check content

System.out.println(sm.equals(sm1));// false, but not getting the reason
// why it is false

/*
* In this case also the content is same but not getting the proper
* conclusion why it is false & it is false then why i am getting true
* in "System.out.println(t.equals(t1))" in this condtion.
*/

System.out.println(s.equals(sm));

}
}

最佳答案

In this case, also the content is same but not getting the proper conclusion why it is false & it is false then why I am getting true in System.out.println(t.equals(t1)) in this condition.

String有一个equals(和hashcode)的实现,它逐个字符地比较两个对象。您的类没有这些方法的实现,因此它使用从 Object 继承的实现,该实现比较引用,即,要使其为 true,实例必须是 相同

这是一个需要您理解的重要区别,相同意味着这两个引用指向完全相同的实例。而等于表示它们要么相同,要么具有等效的内容,但由您来定义如何比较内容,请参阅this .

关于java - .equals() 创建类构造函数并比较简单字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41113226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com