I have an array of Objects (file list excatly). How to iterate through this array and delete some Objects (in Java) - depending on the condition ?
File[] files = file.listFiles();
for(File f: files) {
if(someCondition) {
// remove
}
}
I have an array of Objects (file list excatly). How to iterate through this array and delete some Objects (in Java) - depending on the condition ?
File[] files = file.listFiles();
for(File f: files) {
if(someCondition) {
// remove
}
}
We can't delete elements and resize the arrays in one step/operation. Arrays can't be resized.
Either use a
List
or (1) flag the elements you want to delete and (2) write the elements you want to keep, to a new array.Here's a solution if you want to continue with arrays (
List
is much easier):You need to have the index of the object in the array to be able to remove it:
Note that an array has a fixed length. Removing an element won't shrink the array. If you want this, use a
List<File>
, iterate through the list using anIterator
, and use the iterator'sremove
method to remove the current element.JB Nizet has it exactly right:
You can't "delete" elements from an array
You can set elements to "null". This effectively deletes them (in a C kind of way), but it requires extra logic so you don't accidentally try to reference a null element.
All things being equal, you're probably better off with a List<>, which does allow you to insert and delete elements.
PS: If you know a priori what elements you don't want, the FileFilter idea is an excellent way to keep from getting them in the first place.
You may be better off giving FilenameFilter to
listFiles
and apply condition there. See File documentation http://download.oracle.com/javase/6/docs/api/java/io/File.htmlI think the best Java way to tackle your problem is to convert your array into a list and use an iterator which allows you to remove objects:
You can even convert it again into an array if necessary -even though handling a list is probably more convenient ...:
I suggest to convert it to list and use LambdaJ filter operation: http://code.google.com/p/lambdaj/wiki/LambdajFeatures. Also filter for lists is available in other libraries, like Guava.