Java:如何根据条件从数组中删除对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6646888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How to remove objects from an Array depending on the condition?
提问by marioosh
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 ?
我有一个对象数组(文件列表)。如何遍历这个数组并删除一些对象(在 Java 中) - 取决于条件?
File[] files = file.listFiles();
for(File f: files) {
if(someCondition) {
// remove
}
}
回答by Jean Logeart
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:
我认为解决您的问题的最佳 Java 方法是将您的数组转换为列表并使用允许您删除对象的迭代器:
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();
回答by Alex Gitelman
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.html
您最好给 FilenameFilterlistFiles
并在那里应用条件。请参阅文件文档http://download.oracle.com/javase/6/docs/api/java/io/File.html
回答by Andreas Dolk
We can't deleteelements and resizethe 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.
使用 aList
或 (1) 标记要删除的元素并 (2) 将要保留的元素写入新数组。
Here's a solution if you wantto continue with arrays (List
is much easier):
如果您想继续使用数组,这是一个解决方案(List
更容易):
private File[] filter(File[] files) {
boolean[] deleteFlags = new boolean[files.length];
int deleteCounter = 0;
// collection
for (int i = 0; i < files.length; i++) {
if (deleteConditionIsTrue()) {
deleteFlags[i] = true;
deleteCounter++;
}
}
// create result
File[] result = new File[files.length-deleteCounter];
int gapCounter = 0;
for (int i = 0; i < deleteFlags.length; i++) {
if (deleteFlags[i]) {
gapCounter++; // skip entry, has been filtered/deleted
} else {
result[i-gapCounter] = files[i];
}
}
return result;
}
回答by paulsm4
JB Nizet has it exactly right:
JB Nizet 说得完全正确:
You can't "delete" elements from an array
You canset 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 doesallow you to insert and delete elements.
您不能从数组中“删除”元素
您可以将元素设置为“null”。这有效地删除了它们(以 C 类的方式),但它需要额外的逻辑,因此您不会意外地尝试引用空元素。
所有的事情都是平等的,你可能有过一个更好的名单<>,这也允许你插入和删除元素。
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.
PS:如果您事先知道哪些元素是您不想要的,那么 FileFilter 想法是一个很好的方法,可以避免从一开始就获得它们。
回答by JB Nizet
You need to have the index of the object in the array to be able to remove it:
您需要在数组中拥有对象的索引才能将其删除:
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if(someCondition) {
files[i] = null;
}
}
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 an Iterator
, and use the iterator's remove
method to remove the current element.
请注意,数组具有固定长度。删除元素不会缩小数组。如果需要,请使用 a List<File>
,使用 an 遍历列表Iterator
,并使用迭代器的remove
方法删除当前元素。
回答by dbf
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.
我建议将其转换为列表并使用 LambdaJ 过滤器操作:http: //code.google.com/p/lambdaj/wiki/LambdajFeatures。在其他库中也可以过滤列表,比如 Guava。