📅  最后修改于: 2020-09-26 04:13:53             🧑  作者: Mango
java 字符串 equals()方法根据字符串的内容比较两个给定的字符串。如果任何字符不匹配,则返回false。如果所有字符都匹配,则返回true。
字符串equals()方法将覆盖Object类的equals()方法。
" public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
"public boolean equals(Object anotherObject)
anotherObject:另一个对象,即与此字符串进行比较。
如果两个字符串的字符相等,则为true,否则为false。
Java Object类的equals()方法。
"public class EqualsExample{
public static void main(String args[]){
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}}
"true
false
false
equals()方法比较两个字符串,并且可以在if-else控制结构中使用。
"public class EqualsExample {
public static void main(String[] args) {
String s1 = "javatpoint";
String s2 = "javatpoint";
String s3 = "Javatpoint";
System.out.println(s1.equals(s2)); // True because content is same
if (s1.equals(s3)) {
System.out.println("both strings are equal");
}else System.out.println("both strings are unequal");
}
}
"true
both strings are unequal
让我们再看一个示例,以测试列表中存在的字符串是否相等。
"import java.util.ArrayList;
public class EqualsExample3 {
public static void main(String[] args) {
String str1 = "Mukesh";
ArrayList list = new ArrayList<>();
list.add("Ravi");
list.add("Mukesh");
list.add("Ramesh");
list.add("Ajay");
for (String str : list) {
if (str.equals(str1)) {
System.out.println("Mukesh is present");
}
}
}
}
"Mukesh is present