Convert ArrayList to Array

I’m having a little trouble converting an array list to an array in java.

I have a class called Table which contains an array list called applicants which takes Strings. When I use my toArray() function it doesn’t seem to convert the array list into an array.

I know this because when i run the listArray() function it gives the error:

java.lang.NullPointerException.

Here is the code. Any help would be greatly appreciated.

public class Table {
    public ArrayList<String> applicants;
    public String appArray[];

    public Table() {
        applicants = new ArrayList<String>();
    }

    public void addApplicant(String app) {
        applicants.add(app);
    }

    public void toArray() {
        int x = applicants.size();
        String[] appArray = new String[x];
        appArray = applicants.toArray(appArray);
    }

    public void list() {
        for (int i = 0; i < applicants.size(); i++) {
            System.out.println(applicants.get(i));
        }
    }

    public void listArray() {
        for (int i = appArray.length; i > 0; i--) {
            System.out.println(appArray[i]);
        }
    }
}

Answer

This is because you are shadowing the appArray field in your method here:

 int x = applicants.size();
 String[] appArray = new String[x];
 appArray = applicants.toArray(appArray);

You create a new local variable called appArray when you should be using the appArray field you already have declared in your class.

You should do

public void toArray()
{
    appArray = applicants.toArray(new String[0]);
}

Leave a Reply

Your email address will not be published. Required fields are marked *