java实例化内部类_java-实例化内部类

我正在研究一个过度使用hashCode和equals方法的示例问题,但收到一个错误:“没有可访问类型CustomHashCodeExample的封闭实例。必须使用类型为CustomHashCodeExample的封闭实例(例如xx是A()来限定分配) 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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值