Convert ArrayList to Array

I'm having a little problem converting an array to an array in java.

I have a class called Table that contains a list of named arrays applicants

that accepts strings. When I use my function toArray()

it doesn't convert the array list to an array.

I know this because when I run the listArray () function it throws an 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]);
        }
    }
}

      

+3


source to share


3 answers


This is because you are hiding the field appArray

in your method here:

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

      

You create a new local variable named appArray

when you have to use a field appArray

that you have already declared in your class.



You must do

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

      

+16


source


appArray = new String[applicants.size()];
int index = 0;
for(String app:applicants){
    appArray [index] = app;
    index++;
}

      



+1


source


Since your ArrayList and Array should only have strings, you can do this.

appArray = applicants.toArray(new String[0]);

      

More details in the javadoc .

+1


source







All Articles