From 143bb67c56611674a7eb623f1f1460430212250d Mon Sep 17 00:00:00 2001 From: Martin Goik <goik@hdm-stuttgart.de> Date: Wed, 18 Jan 2023 13:11:47 +0100 Subject: [PATCH] equals() vs. == for Strings --- Doc/Sd1/CoreClasses/coreClasses.xml | 62 ++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/Doc/Sd1/CoreClasses/coreClasses.xml b/Doc/Sd1/CoreClasses/coreClasses.xml index bc5e7ae78..0aa815184 100644 --- a/Doc/Sd1/CoreClasses/coreClasses.xml +++ b/Doc/Sd1/CoreClasses/coreClasses.xml @@ -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) + && (!COMPACT_STRINGS || this.coder == aString.coder) + && StringLatin1.equals(value, aString.value); +}</programlisting> + </figure> + <section xml:id="sw1_sect_CoreClasses_hashing"> <title>Objects, equals() and hash-values</title> -- GitLab