0
I’m having trouble accessing arrays in a Singleton class
Class Info
public class Info {
private static Info cinfo;
private String[] first_name;
private String[] last_name;
private String[] nickname;
public static Info getInstance() {
if (cinfo == null) {
cinfo = new Info();
}
return cinfo;
}
public String getFirst_name(int index) {
return first_name[index];
}
public void setFirst_name(String first_name , int index) {
this.first_name[index] = first_name;
}
public String getLast_name(int index) {
return last_name[index];
}
public void setLast_name(String last_name, int index) {
this.last_name[index] = last_name;
}
public String getNickname(int index) {
return nickname[index];
}
public void setNickname(String nickname, int index) {
this.nickname[index] = nickname;
}
}
Main
public class main {
public static void main(String[] args) {
Info cinfo = new Info();
cinfo.setFirst_name("Lucas", 0);
cinfo.setFirst_name("Bertz", 1);
System.out.println(cinfo.getFirst_name(0));
}
}
Error
Exception in thread "main" java.lang.NullPointerException
at Info.setFirst_name(Info.java:28)
at main.main(main.java:6)
Why are you representing your data this way? Why not use classes? I will answer about the mistake you are having, but I would like to know what the motivation behind this design.
– mgibsonbr
By the way, if you’re instantiating
Info
withnew
, then your class is not Singleton... the builder ofInfo
should be private, and the first line of itsmain
should beInfo cinfo = Info.getInstance();
– mgibsonbr
@mgibsonbr This is just a test
– Lucas Bertollo