如何过滤Java中的数组? [英] How to filter an array in Java?

查看:730
本文介绍了如何过滤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
    }
}

我应该怎么做呢?

How should I do this?

在我的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]);
    }
}

然后我会做与向量的大小的新数组。然后,我会遍历所有的矢量再次填充新数组。我知道这是一些简单的一个非常大的过程。

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类比J2SE载体不同(如这个文件表明 ),那么也许下面的code将工作:

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屋!

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