Java equals are pretty unpleasant

Introduction

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.

What was unpleasant

How do you compare strings when you compare them?

For amateur programmers

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.

For general programmers

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 "==".

Summary

String comparison is the same for equals and "==" ????

No no

** 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.

Summary

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

Java equals are pretty unpleasant
[Java] Difference between == and equals
[Java Silver] About equals method
[Java] HashCode and equals overrides
What are Java metrics? _Memo_20200818
Why are class variables needed? [Java]
[Java beginner] == operator and equals method
Java array variables are reference types
Understanding equals and hashCode in Java
Java local variables are thread safe
[Java] What are overrides and overloads?