/*
* Digit.java
*/
public final class Digit implements Comparable<Digit>{
private final char value;
public Digit(char value) {
if (!Character.isDigit(value)) {
throw new IllegalArgumentException(value + " is not a Digit");
}
this.value = value;
}
public char getValue() {
return value;
}
public int compareTo(Digit anotherDigit) {
return this.value - anotherDigit.value;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Digit other = (Digit) obj;
if (this.value != other.value) {
return false;
}
return true;
}
public int hashCode() {
int hash = 7;
hash = 83 * hash + this.value;
return hash;
}
public String toString() {
return String.valueOf(value);
}
}
public int hashCode() {
int hash = 7;
hash = 83 * hash + this.value;
return hash;
}
Frag mal die Klasse Object :idea:Backwardsman hat gesagt.:was ist denn das für eine sinnfreie funktion :-DCode:public int hashCode() { int hash = 7; hash = 83 * hash + this.value; return hash; }
return 581 + this.value;
Von "sparen" steht nix im "general contract" von hashCode.Backwardsman hat gesagt.:immerhin steht da nichts anderes als
die 581 kann man sich auch sparen... wenns wenigstens ne primzahl wäre!? ;-)Code:return 581 + this.value;
Ja, das war ein Lapsus, danke für den Hinweis :toll:Ark hat gesagt.:Das Interface Comparable wäre auch nicht schlecht ...
Das Beispiel zeigt einfach nur eine allgemein bewährte Vorgehensweise für hashCode.Backwardsman hat gesagt.:mir ist schon klar, dass der hashCode für unterschiedliche objekte mit gleichem value gleichsein muss. mir ging es nur darum, dass man sich die 581 in soweit sparen, kann, dass man auch gleich das value zurückgeben kann. genau so gut, könnte man eine x-beliebige zahl drauf addieren, subtrahieren oder sonst was damit machen. fand es nur sinnfrei, wie die 581 "zusammengebastelt" wird ;-)
public int hashCode(){
return value;
}
public boolean equals(Object o){
if(o instanceof Digit) return compareTo((Digit)o)==0;
return false;
}