In Java, arrays are objects and support object methods such as
Object.equals(). However, arrays do not support any methods besides those provided by
Object. Consequently, using
Object.equals() on any array compares only array references, not their contents. Programmers who wish to compare the contents of two arrays must use the static two-argument
Arrays.equals() method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to
Object.equals(). In other words, two arrays are equal if they contain equivalent elements in the same order. To test for reference equality, use the reference equality operators,
Because the effect of using
Object.equals() to compare two arrays is often misconstrued as content equality, and because a better alternative exists in the use of reference equality operators, the use of the
Object.equals() method to compare two arrays is disallowed.
Noncompliant Code Example
This noncompliant code example uses the
Object.equals() method to compare two arrays:
This compliant solution compares the content of two arrays using the two-argument
This compliant solution compares the array references using the reference equality operators
equals() method or relational operators with the intention of comparing array contents produces incorrect results, which can lead to vulnerabilities.
Static detection of calls to to
Object.equals() is straightforward. However, it is not always possible to statically resolve the class of a method invocation's target. Consequently, it may not always be possible to determine when
Object.equals() is invoked for an array type.
|FB.CORRECTNESS.EC_BAD_ARRAY_COMPARE||Invocation of equals() on an array, which is equivalent to ==|
|S2159||Silly equality checks should not be made|