On 2024/09/26 09:49:50 Alex Tsvetkov wrote:
> Hi.
> 
> I found a bug in the implementation of the method `equals` of class `Pair`.
> 
> Implementation must be symmetric. Current implementation is not.
> 
> Her test showing the problem:
> 
> ```
> 
> @Test
> void run() {
>     var pair = Pair.of("a", "b");
>     var entry = new Map.Entry<String, String>() {
>         public String getKey() { return "a"; }
>         public String getValue() { return "b"; }
>         public String setValue(String value) { return null; }
>     };
>     assertTrue(pair.equals(entry)); // true
>     assertTrue(entry.equals(pair)); // false
> }
> ```

This bug is in the test: The class violates the Map.Entry contract for the 
equals() method, so it's completely broken.

The Javadoc for Map.Entry #equals(Object) in Java 8:

        /**
         * Compares the specified object with this entry for equality.
         * Returns <tt>true</tt> if the given object is also a map entry and
         * the two entries represent the same mapping.  More formally, two
         * entries <tt>e1</tt> and <tt>e2</tt> represent the same mapping
         * if<pre>
         *     (e1.getKey()==null ?
         *      e2.getKey()==null : e1.getKey().equals(e2.getKey()))  &amp;&amp;
         *     (e1.getValue()==null ?
         *      e2.getValue()==null : e1.getValue().equals(e2.getValue()))
         * </pre>
         * This ensures that the <tt>equals</tt> method works properly across
         * different implementations of the <tt>Map.Entry</tt> interface.
         *
         * @param o object to be compared for equality with this map entry
         * @return <tt>true</tt> if the specified object is equal to this map
         *         entry
         */
        boolean equals(Object o);

Gary

> 

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscr...@commons.apache.org
For additional commands, e-mail: user-h...@commons.apache.org

Reply via email to