I am trying to filter out specific strings in an array with the following code, but it keeps crashes when I try to run it.
public String[] lister(String[] fl){
String[] filelist = {};
int j = 0;
for(int i = 0; i < fl.length; i++){
if (fl[i].contains("Incident ")){
filelist[j] = fl[i];
j++;
}
}
return filelist;
}
I already tried some things, and it seems to be that
filelist[j] = fl[i];
is the culprit. When I run
public String[] lister(String[] fl){
String[] filelist = {};
int j = 0;
for(int i = 0; i < fl.length; i++){
if (fl[i].contains("Incident ")){
//filelist[j] = fl[i];
j++;
}
}
filelist = fl;
return filelist;
}
It doesn't crash, even though it runs the forloop. Obviously the result is not what I need.
I don't understand why it does this? For some reason it feels as if it doesn't see 'filelist' initialized in the forloop.
ArrayListinstead or give your array a fixed length.