每当我调用pennyCount方法或removePenny方法时,我都会得到一个空指针异常错误,我不明白,因为我的HashSet应该在构造函数中填充。为什么我得到这个,我该如何解决?
import java.util.HashSet;
public class Pocket
{
private HashSet<Penny> penniesSet;
public Pocket(int numOfPennies){
HashSet<Penny> penniesSet = new HashSet<Penny>();
for(int n = 0; n < numOfPennies; n++){
penniesSet.add(new Penny());}
}
public int pennyCount(){
return penniesSet.size();
}
public Penny removePenny(){
if(penniesSet.size() == 0){
return null;
}
else{
Penny toRemove = penniesSet.iterator().next();
penniesSet.remove(toRemove);
return toRemove;
}
}
}
答案 0 :(得分:1)
在构造函数中创建两个具有相同名称的HashSet,一个字段和一个local。将会发生的是局部变量将被实例化。到达pennyCount()时,该字段仍为空。
private HashSet<Penny> penniesSet; //first here
public Pocket(int numOfPennies){
HashSet<Penny> penniesSet = new HashSet<Penny>(); //then here
要纠正这样做。
private HashSet<Penny> penniesSet;
public Pocket(int numOfPennies){
penniesSet = new HashSet<Penny>();
答案 1 :(得分:0)
在构造函数中,您有以下
HashSet<Penny> penniesSet = new HashSet<Penny>();
应该是
penniesSet = new HashSet<Penny>();
答案 2 :(得分:0)
在构造函数中,您声明了一个新的HashSet penniesSet,它应该是:
public Pocket(int numOfPennies){
penniesSet = new HashSet<Penny>();
for(int n = 0; n < numOfPennies; n++){
penniesSet.add(new Penny());}
}
否则你的pennieSet永远不会被初始化。
答案 3 :(得分:0)
尝试
public Pocket(int numOfPennies){
penniesSet = new HashSet<Penny>(); // was HashSet<Penny> penniesSet = new HashSet<Penny>();
for(int n = 0; n < numOfPennies; n++){
penniesSet.add(new Penny());}
}
答案 4 :(得分:0)
这样改变。
public Pocket(int numOfPennies){
penniesSet = new HashSet<Penny>();
for(int n = 0; n < numOfPennies; n++){
penniesSet.add(new Penny());}
}
答案 5 :(得分:0)
变化
public Pocket(int numOfPennies){
HashSet<Penny> penniesSet = new HashSet<Penny>();
for(int n = 0; n < numOfPennies; n++){
penniesSet.add(new Penny());}
}
到
public Pocket(int numOfPennies){
penniesSet = new HashSet<Penny>(); //set the instance variable instead of creating a local variable
for(int n = 0; n < numOfPennies; n++){
penniesSet.add(new Penny());}
}
答案 6 :(得分:0)
您正在构造函数中创建新的Set对象,而不是填充类的字段。尝试:
penniesSet = new HashSet<Penny>();