63 lines
1.2 KiB
Plaintext
63 lines
1.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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
|
|
|
|
[source,java]
|
|
----
|
|
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
|
|
|
|
[source,java]
|
|
----
|
|
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)
|
|
|
|
include::message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|