Java:如何根据条件从数组中删除对象? [英] Java: How to remove objects from an Array depending on the condition?

查看:1011
本文介绍了Java:如何根据条件从数组中删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组(文件列表)。如何迭代这个数组并删除一些对象(用Java) - 取决于条件?

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 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:

List<File> files = new ArrayList<File>(Arrays.asList(file.listFiles()));
Iterator<File> iterator = files.iterator();
while(iterator.hasNext()){
    File currentFile = iterator.next();
    if(someCondition){
        iterator.remove();
    }
    // other operations
}

你甚至可以如果需要,将它再次转换为数组 - 尽管处理列表可能更方便......:

You can even convert it again into an array if necessary -even though handling a list is probably more convenient ...:

File[] filesArray = files.toArray();

这篇关于Java:如何根据条件从数组中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆