Problem with Getters and Setters of an Array

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)
    
asked by anonymous 19.07.2014 / 06:47

1 answer

2

Your error occurs because the first_name array is not instantiated (i.e. it is null ). When attempting to access it, NullPointerException occurs.

In Java, arrays have a fixed size, so you can not create a simple array that resizes to receive new elements (for that, it is best to use java.util.ArrayList ). So, you need to choose a default size for your array (s), and already in the constructor (or at instance initialization) create an array of that size:

public class Info {
    private static Info cinfo;

    private String[] first_name = new String[10];
    private String[] last_name = new String[10];
    private String[] nickname = new String[10];

In this way, you will have an array with 10 elements, all null . Your assignment will be successful, provided the index is of course within the acceptable range (% with% to% with%). That is, it is important to check this in the function call, and react accordingly (throwing an exception, replacing the array with a larger one, etc.).

    
19.07.2014 / 07:21