简体   繁体   中英

Can I iterate over two arrays at once in Java?

For one array I can iterate like this:

for(String str:myStringArray){

}

How can I iterate over two arrays at once? Because I am sure these two's length are equal.I want it like the following:

for(String attr,attrValue:attrs,attrsValue) {

}

But it's wrong.

Maybe a map is a good option in this condition, but how about 3 equal length arrays? I just hate to create index 'int i' which used in the following format:

for(int i=0;i<length;i++){
}

You can't do what you want with the foreach syntax, but you can use explicit indexing to achieve the same effect. It only makes sense if the arrays are the same length (or you use some other rule, such as iterating only to the end of the shorter array):

Here's the variant that checks the arrays are the same length:

assert(attrs.length == attrsValue.length);
for (int i=0; i<attrs.length; i++) {
   String attr = attrs[i];
   String attrValue = attrsValue[i];
   ...
}

You can do it old fashion way.

Assuming your arrays have same sizes:

for(int i = 0; i < array1.length; i++) {
   int el1 = array1[i];
   int el2 = array2[i];
}

In Scala there is an embedded zip function for Collections, so you could do something like

array1 zip array2

but it's not yet ported to Java8 Collections.

Foreach loop has many advantages but there are some restriction are also there.

1: You can iterate only one class(which implements Iterable i/f) at one time.

2: You don't have indexing control. (use explicit counter for that.)

For your problem use legacy for loop .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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