Java 教程 Java String equals() 方法

savoy · 2022-05-26 23:59:54 · 热度: 13

equals() 方法用于将字符串与指定的对象比较。

String 类中重写了 equals() 方法用于比较两个字符串的内容是否相等。

语法

public boolean equals(Object anObject)

参数

  • anObject -- 与字符串进行比较的对象。

返回值

如果给定对象与字符串相等,则返回 true;否则返回 false。

实例

实例

public class Test {
    public static void main(String args[]) {
        String Str1 = new String("codercto");
        String Str2 = Str1;
        String Str3 = new String("codercto");
        boolean retVal;

        retVal = Str1.equals( Str2 );
        System.out.println("返回值 = " + retVal );

        retVal = Str1.equals( Str3 );
        System.out.println("返回值 = " + retVal );
    }
}

以上程序执行结果为:

返回值 = true
返回值 = true

使用 ==equals() 比较字符串。

String 中 == 比较引用地址是否相同,equals() 比较字符串的内容是否相同:

String s1 = "Hello";              // String 直接创建
String s2 = "Hello";              // String 直接创建
String s3 = s1;                   // 相同引用
String s4 = new String("Hello");  // String 对象创建
String s5 = new String("Hello");  // String 对象创建
 
s1 == s1;         // true, 相同引用
s1 == s2;         // true, s1 和 s2 都在公共池中,引用相同
s1 == s3;         // true, s3 与 s1 引用相同
s1 == s4;         // false, 不同引用地址
s4 == s5;         // false, 堆中不同引用地址
 
s1.equals(s3);    // true, 相同内容
s1.equals(s4);    // true, 相同内容
s4.equals(s5);    // true, 相同内容

查看更多 Java String 类 相关内容

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册