【发布时间】:2011-05-03 12:17:39
【问题描述】:
我正在处理覆盖 hashCode 和 equals 方法的示例问题,但出现错误:“没有可访问类型 CustomHashCodeExample 的封闭实例。必须使用 CustomHashCodeExample 类型的封闭实例来限定分配(egxnew A () 其中 x 是 CustomHashCodeExample 的一个实例)。" 我编写了一个内部类 HashPerson,当我尝试在另一个名为 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;
}
}
【问题讨论】:
-
您真的阅读了错误信息吗?它确切地告诉你该怎么做。实例化内部类时,必须使用封闭类的实例对其进行限定。
-
您应该真正清理示例代码的格式并将其剥离到基本要素。在目前的状态下,这几乎是不可读的。
-
您可以将
hashCode方法简化为return name.hashCode(); -
@Jonik:感谢您清理代码格式。我还没有足够的声誉来做那件事。不过,这让我有点困惑。当我查看代码时,它应该会产生相同的“无封闭实例”错误,因为静态方法
testHashCodeOverride想要实例化非静态嵌套(=inner)类HashPerson的对象。 -
@Steve,这是一个展示如何在所有场景中覆盖哈希码的示例,我只是自己尝试相同。名称.hashCode();会返回我的内存地址,对吗?
标签: java inner-classes