Sto lavorando su un problema di esempio di metodo hashCode e equals over-ridding ma ricevendo un errore: "Nessuna istanza di inclusione di tipo CustomHashCodeExample è accessibile. Deve qualificare l'allocazione con un'istanza allegata di tipo CustomHashCodeExample (egxnew A() dove x è un'istanza di CustomHashCodeExample). " Ho scritto una classe interna HashPerson e sto ricevendo questo errore quando sto provando a creare un'istanza di questa classe interna in un altro metodo chiamato testHashCodeOverride().Classe interna di istanziazione
public static void testHashCodeOverride(){
System.out.println("\nTest HashCode Override Method");
System.out.println("==================================\n");
HashPerson william = new HashPerson("willy");
HashPerson bill = new HashPerson("willy");
}
Questo codice funziona bene, anche se non vedo classe interna statica o di un'istanza di classe esterna, confuso :(
public class HashCodeExample {
public static void testHashCodeOverride() {
HashPerson william = new HashPerson("Willy");
HashPerson bill = new HashPerson("Willy");
System.out.println("Hash code for william = " + william.hashCode());
System.out.println("Hash code for bill = " + bill.hashCode());
HashMap table = new HashMap();
table.put(william, "Silly");
if (table.containsKey(william)) {
System.out.println(table.get(william));
} else {
System.out.println("Key " + william + " not found");
}
if (table.containsKey(bill)) {
System.out.println(table.get(bill));
} else {
System.out.println("Key " + bill + " not found");
}
}
class HashPerson {
private static final int HASH_PRIME = 1000003;
public HashPerson(String name) {
this.name = name;
}
public String toString() {
return name;
}
public boolean equals(Object rhs) {
if (this == rhs)
return true;
// make sure they are the same class
if (rhs == null || rhs.getClass() != getClass())
return false;
// ok, they are the same class. Cast rhs to HashPerson
HashPerson other = (HashPerson) rhs;
// our test for equality simply checks the name field
if (!name.equals(other.name)) {
return false;
}
// if we get this far, they are equal
return true;
}
public int hashCode() {
int result = 0;
result = HASH_PRIME * result + name.hashCode();
return result;
}
private String name;
}
}
Hai effettivamente letto il messaggio di errore? Ti dice ** esattamente ** cosa fare. Quando si crea un'istanza di una classe interna, deve essere qualificata con un'istanza della classe che la include. –
Si dovrebbe davvero pulire la formattazione del codice di esempio e ridurlo all'essenziale. Nel suo stato attuale questo è praticamente illeggibile. – MForster
È possibile semplificare il metodo 'hashCode' solo per' return name.hashCode(); ' –