[英]NullPointerException, can't understand why
I'm trying to make this java exercise, but i receive a NullPointerException and i can't understand why 我正在尝试进行此Java练习,但是我收到了NullPointerException,但我不明白为什么
public class CV
{
private String nome;
private HashSet<Pubblicazione> pubblicazioni;
public CV(String nome)
{
this.nome = nome;
}
public void aggiungiPubblicazione(Pubblicazione pub)
{
pubblicazioni.add(pub);(*)
}
public String getNome(){return nome;}
public HashSet<Pubblicazione> getPubblicazioni(){ return pubblicazioni; }
}
public class ProfEvaluator
{
private CV curriculum;
public ProfEvaluator(CV curriculum){ this.curriculum = curriculum; }
public static void main(String[] args)
{
CV cv = new CV("Mario Rossi");
cv.aggiungiPubblicazione(new Pubblicazione("pub1",10, "Mario Rossi", "Luigi Bianchi", "Giuseppe Verdi")); (*)
cv.aggiungiPubblicazione(new Pubblicazione("pub2",10, "Mario Rossi", "Giuseppe Verdi"));
}
}
The output is : 输出为:
Exception in thread "main" java.lang.NullPointerException
at CV.aggiungiPubblicazione(CV.java:18)
at ProfEvaluator.main(ProfEvaluator.java:53)
I've made a debug with eclipse and there are no NullPointers. 我用eclipse进行了调试,没有NullPointers。 The exception is thrown in the line marked with (*) (the lines indicated by the error messages are wrong 'cause i've pasted only the parts of the program that i considered involved with the error.
在标有(*)的行中引发异常(错误消息指示的行是错误的,因为我仅粘贴了我认为与错误有关的程序部分。
You do have a null pointer. 您确实有一个空指针。 You try to access
pubblicazioni
before instantiating it. 您尝试在实例化之前访问
pubblicazioni
。
You can add to the constructor: 您可以添加到构造函数中:
public CV(String nome)
{
this.nome = nome;
this.pubblicazioni = new HashSet<>();
}
As @ZouZou stated: 正如@ZouZou所说:
If you're not dealing with Java 7, replace = new HashSet<>();
如果您不使用Java 7,请替换
= new HashSet<>();
with = new HashSet<Pubblicazione>();
与
= new HashSet<Pubblicazione>();
在向其添加值之前初始化HashSet pubblicazioni
。
You need to initialize pubblicazioni
before using it: 您需要在使用之前初始化
pubblicazioni
:
public CV(String nome)
{
this.nome = nome;
this.pubblicazioni = new HashSet<Pubblicazione>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.