简体   繁体   English

使用循环从另一个数组创建一个数组

[英]creating an array from another array using a loop

I am Passing an Array into a for loop with an if statment, I am want to have all the elements that evaluate true be added to a new array.我正在将一个数组传递到一个带有 if 语句的 for 循环中,我希望将所有评估为 true 的元素添加到一个新数组中。 How Do I do This?我该怎么做呢?

Supposing you have an object array, and you want to create a possibly smaller array containing the elements that satisfy some predicate, you are faced with the problem of knowing how big to make the new array.假设您有一个对象数组,并且您想创建一个包含满足某些谓词的元素的可能较小的数组,您将面临知道新数组有多大的问题。 You can determine that only by testing each starting element against the predicate, which you would normally prefer to avoid doing twice.您只能通过针对谓词测试每个起始元素来确定这一点,您通常希望避免这样做两次。 One way to approach the problem would be to use a List to temporarily hold the elements you want to collect:解决该问题的一种方法是使用List临时保存要收集的元素:

MyElementType[] myArray = { /* ... */ };
MyElementType[] result;
List<MyElementType> temp = new ArrayList<MyElementType>();

for (MyElementType element : myArray) {
    if (passesMyTest(element)) {
        temp.add(element);
    }
}

result = temp.toArray(new MyElementType[0]);

Of course, it's usually easier to work directly with List s instead of with arrays, but sometimes you don't have that luxury.当然,直接使用List而不是数组通常更容易,但有时您没有那种奢侈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM