每當我調用pennyCount方法或removePenny方法,我得到一個空指針異常錯誤,我不明白,因爲我的HashSet應該填充在構造函數中。爲什麼我得到這個,我該如何解決它?爲什麼我收到java.lang.NullPointerException錯誤
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;
}
}
}
東西是空的。所以你得到NullPointerException。:) – subash 2014-12-02 14:59:26