Hello, this is Kechon. ** Are you writing Java? ** ** I haven't coded in the last few months. I hurriedly started studying Java gold (from today) I would like to introduce it because I felt uncomfortable at that time.
How do you compare strings when you compare them?
String str1 = "test";
String str2 = "test";
if (str1 == str2) {
System.out.print("same");
} else {
System.out.print("diff");
}
Yes, it's no good. I get angry if I write this code. Yes, I am. The operator "==" compares the memory addresses of objects.
Different objects basically have different memory addresses. This time I want to compare the character string of the object, which is against my intention.
**, but in this case "same" is output. ** ** Be careful because the String itself is unpleasant. It is not the main subject and I do not know it in detail, so I will omit it.
String str1 = "1";
String str2 = "1";
if (str1.equals(str2)) {
System.out.print("same");
} else {
System.out.print("diff");
}
It's normal. I often see it. But have you ever seen the contents of Object.equals?
The contents are ...
public boolean equals(Object obj) {
return (this == obj);
}
** "==" Use it!
I was angry when I was angry with "==".
String comparison is the same for equals and "==" ????
** Of course not. ** **
The equals method is overridden by the String class. Below is the contents of String.equals.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
This also uses "==", but if the memory address is different, you are doing another comparison.
Object.equals is just a comparison with "==" String.equals is compared with "==", but if the comparison target is a character string, it behaves specially (this is the expected movement)
Recommended Posts