मैं ओवर-राइडिंग हैशकोड की नमूना समस्या पर काम कर रहा हूं और विधि के बराबर है लेकिन त्रुटि प्राप्त कर रहा है: "कस्टमहैशकोडएक्स नमूना प्रकार का कोई भी संलग्न उदाहरण उपलब्ध नहीं है। कस्टमशैशकोडएक्स नमूना (उदाहरण के लिए एक संलग्न उदाहरण के साथ आवंटन को अर्हता प्राप्त करना चाहिए) ए() जहां x कस्टम हैशकोडएक्स नमूना का उदाहरण है) " मैंने एक आंतरिक वर्ग हैशपर्सन लिखा और मुझे यह त्रुटि मिल रही है जब मैं testHashCodeOverride() नामक किसी अन्य विधि में इस आंतरिक कक्षा को तुरंत चालू करने का प्रयास कर रहा हूं।आंतरिक कक्षा
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");
}
इस कोड को ठीक काम करता है, भले ही मैं स्थिर भीतरी वर्ग या बाहरी वर्ग के इन्स्टेन्शियशन देख न, उलझन :(
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;
}
}
क्या आपने वास्तव में त्रुटि संदेश पढ़ा था? यह आपको ** बिल्कुल ** बताता है कि क्या करना है। एक आंतरिक वर्ग को तुरंत चालू करते समय, इसे संलग्न कक्षा के उदाहरण के साथ योग्यता प्राप्त करनी चाहिए। –
आपको वास्तव में उदाहरण कोड के स्वरूपण को साफ करना चाहिए और इसे आवश्यकतानुसार नीचे ले जाना चाहिए। अपने वर्तमान राज्य में यह काफी अपठनीय है। – MForster
आप अपने 'hashCode' विधि को सरल बनाने के सिर्फ' name.hashCode वापस जाने के लिए कर सकते हैं(); ' –