rspec/rules/S2116/java/rule.adoc

56 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
While ``++hashCode++`` and ``++toString++`` are available on arrays, they are largely useless. ``++hashCode++`` returns the array's "identity hash code", and ``++toString++`` returns nearly the same value. Neither method's output actually reflects the array's contents. Instead, you should pass the array to the relevant static ``++Arrays++`` method.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public static void main( String[] args )
{
String argStr = args.toString(); // Noncompliant
int argHash = args.hashCode(); // Noncompliant
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public static void main( String[] args )
{
String argStr = Arrays.toString(args);
int argHash = Arrays.hashCode(args);
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Use "Arrays.hashCode(array)" instead.
* Use "Arrays.toString(array)" instead.
'''
== Comments And Links
(visible only on this page)
=== on 10 Oct 2014, 15:25:37 Freddy Mallet wrote:
My 2 cents @Ann:
* I would prefer a rule title like "hashCode" and "toString" methods should never be called on array instances
* I would increase the severity to "Critical"
=== on 15 Jul 2016, 14:24:30 Ann Campbell wrote:
https://github.com/google/error-prone/blob/master/docs/bugpattern/ArrayHashCode.md
endif::env-github,rspecator-view[]