2023-05-03 11:06:20 +02:00
== Why is this an issue?
2020-06-30 12:48:07 +02:00
Comparisons of dissimilar types will always return false. The comparison and all its dependent code can simply be removed. This includes:
2020-06-30 14:49:38 +02:00
2020-06-30 12:48:07 +02:00
* comparing an object with null
* comparing an object with an unrelated primitive (E.G. a string with an int)
* comparing unrelated classes
2021-01-27 13:42:22 +01:00
* comparing an unrelated ``++class++`` and ``++interface++``
* comparing unrelated ``++interface++`` types
2020-06-30 12:48:07 +02:00
* comparing an array to a non-array
* comparing two arrays
2021-01-27 13:42:22 +01:00
Specifically in the case of arrays, since arrays don't override ``++Object.equals()++``, calling ``++equals++`` on two arrays is the same as comparing their addresses. This means that ``++array1.equals(array2)++`` is equivalent to ``++array1==array2++``.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
However, some developers might expect ``++Array.equals(Object obj)++`` to do more than a simple memory address comparison, comparing for instance the size and content of the two arrays. Instead, the ``++==++`` operator or ``++Arrays.equals(array1, array2)++`` should always be used with arrays.
2020-06-30 12:48:07 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2020-06-30 12:48:07 +02:00
----
interface KitchenTool { ... };
interface Plant {...}
public class Spatula implements KitchenTool { ... }
public class Tree implements Plant { ...}
//...
Spatula spatula = new Spatula();
KitchenTool tool = spatula;
KitchenTool [] tools = {tool};
Tree tree = new Tree();
Plant plant = tree;
Tree [] trees = {tree};
if (spatula.equals(tree)) { // Noncompliant; unrelated classes
// ...
}
else if (spatula.equals(plant)) { // Noncompliant; unrelated class and interface
// ...
}
else if (tool.equals(plant)) { // Noncompliant; unrelated interfaces
// ...
}
else if (tool.equals(tools)) { // Noncompliant; array & non-array
// ...
}
else if (trees.equals(tools)) { // Noncompliant; incompatible arrays
// ...
}
else if (tree.equals(null)) { // Noncompliant
// ...
}
----
2023-05-03 11:06:20 +02:00
== Resources
2020-06-30 12:48:07 +02:00
2020-12-21 15:38:52 +01:00
* https://wiki.sei.cmu.edu/confluence/x/5zdGBQ[CERT, EXP02-J.] - Do not use the Object.equals() method to compare two arrays
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]