如何在Java中过滤数组? [英] How to filter an array in Java?
问题描述
如何在 Java 中过滤数组?
How can I filter an array in Java?
我有一组对象,例如汽车:
I have an array of objects, for example cars:
类:
public class Car{
public int doors;
public Car(int d){
this.doors = d;
}
}
使用:
Car [] cars = new Cars[4];
cars[0] = new Car(3);
cars[1] = new Car(2);
cars[2] = new Car(4);
cars[3] = new Car(6);
现在我想过滤汽车数组,只保留 4 扇门和更多:
Now I want to filter the array of cars, keeping only 4 doors and more:
for(int i = 0; i<cars.length; i++){
if(cars[i].doors > 4)
//add cars[i] to a new array
}
}
我该怎么做?
在我使用 Vector 之前:
Before I did it with a Vector:
Vector subset = new Vector();
for(int i = 0; i<cars.length; i++){
if(cars[i].doors > 4)
//add cars[i] to a new array
subset.addElement(cars[i]);
}
}
然后我将创建一个具有 Vector 大小的新数组.然后我会再次遍历向量并填充新数组.我知道对于简单的事情来说这是一个非常大的过程.
And then I would make a new array with the size of the Vector. Then I would loop over the vector again and fill the new array. I know this is a very large procedure for something simple.
我使用的是 J2ME.
推荐答案
看到 ArrayList 不在 J2ME 中,但根据文档,它确实有一个 Vector.如果该 Vector 类与 J2SE Vector 不同(如 本文档表示),那么下面的代码可能会起作用:
saw that ArrayList is not in J2ME, but based on documentation, it does have a Vector. If that Vector class is different than J2SE Vector (as this documentation indicates), then perhaps the following code would work:
Vector carList = new Vector();
for(int i = 0; i<cars.length; i++){
if(cars[i].doors > 4)
carList.addElement(cars[i]);
}
}
Car[] carArray = new Car[carList.size()];
carList.copyInto(carArray);
这篇关于如何在Java中过滤数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!