📜  Java字符串equals()(1)

📅  最后修改于: 2023-12-03 14:43:00.493000             🧑  作者: Mango

Java字符串equals()

在Java中,字符串是很常见的数据类型,而字符串的比较操作也是经常用到的。其中,equals()方法是比较字符串内容的一种方式。本文将介绍equals()方法的用法以及一些注意事项。

简介

equals()是String类的方法,用于比较两个字符串是否相等。它的语法如下:

boolean equals(Object anObject)

其中,anObject是需要进行比较的字符串对象。如果这个对象与原字符串内容相等,则返回true,否则返回false

使用方法

equals()方法是区分大小写的,这意味着它会把大写字母和小写字母视为不同的字符。下面是一个简单的例子:

String str1 = "hello";
String str2 = "HELLO";

if(str1.equals(str2))
    System.out.println("Strings are equal.");
else
    System.out.println("Strings are not equal.");

输出为:

Strings are not equal.

因为str1str2中的字符大小写不同。

如果希望进行不区分大小写的比较,则可以使用equalsIgnoreCase()方法。例如:

String str1 = "hello";
String str2 = "HELLO";

if(str1.equalsIgnoreCase(str2))
    System.out.println("Strings are equal.");
else
    System.out.println("Strings are not equal.");

输出为:

Strings are equal.

此时,str1str2被认为是相等的,因为它们的字符相同,只是大小写不同。

注意事项

在使用equals()方法进行字符串比较时,需要注意以下几点:

  1. 字符串比较时,应该先判断是否为null,否则可能会出现空指针异常。

  2. 如果两个字符串长度不同,则它们肯定不相等。

  3. 相等的字符串对象具有相同的hashCode值。因此,如果两个字符串的hashCode值不同,则它们肯定不相等。

  4. 对于字符串常量,可以使用==进行比较。例如:

    String str1 = "hello";
    String str2 = "hello";
    
    if(str1 == str2)
        System.out.println("Strings are equal.");
    else
        System.out.println("Strings are not equal.");
    

    输出为:

    Strings are equal.
    

    因为str1str2中的内容相同,它们指向同一个字符串常量。

  5. 对于字符串对象,不能使用==进行比较。例如:

    String str1 = new String("hello");
    String str2 = new String("hello");
    
    if(str1 == str2)
        System.out.println("Strings are equal.");
    else
        System.out.println("Strings are not equal.");
    

    输出为:

    Strings are not equal.
    

    因为str1str2是两个不同的字符串对象,它们的引用并不相同。

结论

equals()方法是在Java中比较字符串内容的一种方式。在使用时,需要注意字符串大小写、空指针异常、字符串长度以及字符串对象引用等问题。通过这篇文章的介绍,希望读者能够更加深入地了解equals()方法,且能够在实际工作中灵活应用。