本文介绍了我可以在Java中一次迭代两个数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个数组,我可以这样迭代:

  for(String str:myStringArray){

}

如何一次迭代两个数组?
因为我确定这两个长度相等,所以我希望如下所示:

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

}

但这是错误的。 / p>

在这种情况下,也许映射是一个不错的选择,但是3个等长数组呢?我只是讨厌创建索引'int i',它以以下格式使用:

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


解决方案

您无法使用foreach语法执行所需的操作,但是可以使用显式索引来达到相同的效果。仅在数组长度相同时才有意义(或者您使用其他规则,例如仅迭代到较短数组的末尾):



这里是变量检查数组的长度是否相同:

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


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];
   ...
}

这篇关于我可以在Java中一次迭代两个数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:30
查看更多