t0m*_*cat 45 java inner-classes
我正在研究过度散列hashCode和equals方法的示例问题,但是得到一个错误:" 没有可以访问CustomHashCodeExample类型的封闭实例.必须使用CustomHashCodeExample类型的封闭实例来限定分配(例如,xnew A(),其中x是一个实例of 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");
}
Run Code Online (Sandbox Code Playgroud)
这段代码工作正常,即使我没有看到静态内部类或外部类的实例化,困惑:(
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;
}
}
Run Code Online (Sandbox Code Playgroud)
MFo*_*ter 127
我想你想把这个HashPerson类声明为static.否则,它只能在包含类的上下文中实例化,无论是在包含类的方法中还是使用如下代码:
ContainingClass container = new ContainingClass();
HashPerson william = container.new HashPerson("willy");
Run Code Online (Sandbox Code Playgroud)
实际上,我的经验法则是使任何嵌套类都是静态的,除非我有特殊的理由不这样做.这也更有效,因为非静态嵌套类(称为内部类)总是包含对包含对象的隐式引用.
您需要使内部类静态,或通过外部类的实例引用它.很可能你只是想让你的内部类静态.
类的非静态成员(变量,方法,内部类)是类的每个实例.因此,当从静态上下文(例如静态方法testHashCodeOverride)访问非静态成员时,您需要指定封闭类的实例.
| 归档时间: |
|
| 查看次数: |
68354 次 |
| 最近记录: |