Skip to content
Snippets Groups Projects
Commit 143bb67c authored by Goik Martin's avatar Goik Martin
Browse files

equals() vs. == for Strings

parent c3581887
No related branches found
No related tags found
No related merge requests found
......@@ -202,11 +202,71 @@ equals: true</screen></td>
<listitem>
<para>The <methodname
xlink:href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)">equals()</methodname>
method compares two object's values.</para>
method defines the equality two objects.</para>
</listitem>
</itemizedlist>
</figure>
<figure xml:id="sd1_coreclasses_fig_operatorEqualVsMathImply">
<title>Operator == and <methodname>equals()</methodname>
implications</title>
<itemizedlist>
<listitem>
<para>Each object is equal by value to itself:</para>
<para><code>object1 == object2</code>
<code>object1.equals(object2)</code></para>
</listitem>
<listitem>
<para>The converse is not true. Two different objects may be of common
value:</para>
<informaltable border="0">
<colgroup width="44%"/>
<colgroup width="56%"/>
<tr>
<th>Code</th>
<th>Result</th>
</tr>
<tr>
<td valign="top"><programlisting language="java">String s = "Hello", copy = new String(s);
System.out.println("equals: " + s.equals(copy));
System.out.println(" ==: " + (s == copy));</programlisting></td>
<td valign="top"><screen>equals: true
==: false</screen></td>
</tr>
</informaltable>
</listitem>
</itemizedlist>
</figure>
<figure xml:id="sd1_coreclasses_fig_equalsByDefinition">
<title><methodname>equals()</methodname> is being defined within
respective class!</title>
<para>Implementation at <link
xlink:href="https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/String.java">https://github.com/openjdk/
.../String.java</link> :</para>
<programlisting language="java">public final class String ... {
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
return (anObject instanceof String aString)
&amp;&amp; (!COMPACT_STRINGS || this.coder == aString.coder)
&amp;&amp; StringLatin1.equals(value, aString.value);
}</programlisting>
</figure>
<section xml:id="sw1_sect_CoreClasses_hashing">
<title>Objects, equals() and hash-values</title>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment