rspec/rules/S2141/java/rule.adoc

68 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Because ``++Object++`` implements ``++hashCode++``, any Java class can be put into a hash structure. However, classes that define ``++equals(Object)++`` but not ``++hashCode()++`` aren't truly hash-able because instances that are equivalent according to the ``++equals++`` method can return different hashes.
=== 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 class Student { // no hashCode() method; not hash-able
// ...
public boolean equals(Object o) {
// ...
}
}
public class School {
private Map<Student, Integer> studentBody = // okay so far
new HashTable<Student, Integer>(); // 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 class Student { // has hashCode() method; hash-able
// ...
public boolean equals(Object o) {
// ...
}
public int hashCode() {
// ...
}
}
public class School {
private Map<Student, Integer> studentBody = new HashTable<Student, Integer>();
// ...
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Add a "hashCode()" method to "className" or remove it from this hash.
'''
== Comments And Links
(visible only on this page)
=== on 11 Oct 2014, 11:55:56 Freddy Mallet wrote:
Perfect and relates to RSPEC-1206 without any overlap.
endif::env-github,rspecator-view[]