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]);
}
}
}
source to share
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]);
}
source to share