我需要将特定元素从数组复制到新数组。例如:一个 Fruits 数组中包含苹果和橙子,我只想从中获取苹果到一个名为 Apples 的新数组中。
谢谢你。
全部在伪代码中:
你可以做的第一件事:
Fruit[] oArray = ....;
int noOfApple = 0;
for each Fruit f in oArray {
if (f is apple) {
noOfApple++;
}
}
Fruit[] newArray = new Fruit[noOfApple];
int index = 0;
for each Fruit f in oArray {
if (f is apple) {
newArray[index++] = f;
}
}
好吧,因为您正在显式创建新数组,所以您必须先找出大小,然后才能实际创建新数组。为了使它更容易,你可以做类似的事情
List<Fruit> newFruits = new ArrayList<Fruit>();
for each Fruit f in oArray {
if (f is apple) {
newFruits.add(f);
}
}
Fruit[] newArray = newFruits.toArray();
我认为提示应该已经绰绰有余
如果您想做一些更酷的事情,请尝试使用 Guava。您可以执行以下操作(大部分代码都是实际的,带有一些伪代码):
Fruit[] result =
Iterables.filter(Array.asList(oArray),
new Predicate<Fruit>(){
@Override
boolean apply(Fruit f) { return (f is apple);}
})
.toArray();
您可以使用instanceof
运算符来检查水果是否是苹果。之后,只需对数组进行迭代,将所选元素添加到另一个数组。
我建议使用 ArrayList。使用 ArrayList,您可以向其中动态添加项目。
for (int i = 0; i < fruits.size(); i++)
{
if (fruits.get(i) instanceof apple)
apples.add(fruits.get(i));
}
如果你还想要一堆苹果。Apple[] arrayOfApples = apples.ToArray();