我有一个类型的功能: 我可以按如下方式迭代数组。 (标准示例) 数组可以循环,元素返回变量x,如下所示。
public Map<String, String> (Object ... args)
{
. . .
for( Object x : args); // do stuff
. . .
dummyUsexAndPrint(x); // just demonstrating that we can now use x
// x will vary on each loop iteration.
}
我的目标是在不进行任何算术的情况下从数组中创建键值对。 我们可以迭代一个循环&#34;两个两个&#34;? 像这样的东西----&gt;
public Map<String, String> (Object ... args)
{
. . .
for( Object X : args, Object Y : args) {
globalMap.put(X,Y); // using X and Y now, instead of just "x"
//in the previous case
}
. . .
}
第一种情况与模式(a_1, a_2 ...).
匹配
虽然,我需要匹配模式(a_1, a_2, a_3 ...)
并在每次循环运行时提取a_1和a_2。
这种模式匹配在Java中是否可行? 我没有遇到任何这样的例子,只是想验证。
编辑:
假设我们有一个数组[1,2,3,4,5,6]。
像
这样的简单循环for (int x : array) { ...}
会给我x 1 2 3 4 五 6
我想要的是一次获得2个值。
for (int x,y : array) { ... }
1 2
3 4
5 6
其中左手值为x,右手值为y。
编辑2:
for (int i = 0 ; i == array.length - 1; i += 2)
{
x = array[i];
y = array[i + 1];
print(x, y);
}
这清楚了吗?
编辑:似乎没有办法逃避算术。我希望我的数组迭代可以在不进行算术的情况下完成,并且它会抛出异常(这样我就不必检查偶数/赔率)。
合同将是循环一次挑选2个成员并循环。如果没有成员离开,合同就履行了,如果剩下一个成员,则一次分解两个值的合同被违反并抛出异常。
没有这样的运气,在某些语言中,可以直接匹配模式,而不是编写原始循环。我是Java的新手,所以正在探索。
答案 0 :(得分:1)
这两个答案都假定集合的长度是均匀的(因为很明显,如果不是,那么每个y
都不会总是x
。< / p>
T[] args
:
for (int i = 0; i < args.length; i+=2) {
T x = args[i];
T y = args[i+1];
// ... use x and y, e.g. System.out.println(x + " " + y);
}
对于T
s的一般集合:
boolean even = true;
T x = null;
for (T obj : args) {
if (even) {
x = obj;
} else {
T y = obj;
// use x and y, e.g. System.out.println(x + " " + y);
}
even ^= true; // flip even
}
答案 1 :(得分:0)
这就是你要找的东西:
for (int i = 0; i < args.length - 1; )
{
int x = args[i];
int y = args[++i];
i++;
System.out.println(x + " " + y);
}
答案 2 :(得分:0)
尝试像这样使用Deque ..
import java.util.*;
Deque<String> queue = new LinkedList<>(Arrays.asList(new String[] { "1", "2", "3", "4" }));
Map<String, String> data = new HashMap<>();
for (int i = 0; i < queue.size(); i++)
data.put(queue.pop(), queue.pop());
或者您可以使用这样的迭代器代替for循环
while (queue.iterator().hasNext()) {
data.put(queue.pop(), queue.pop());
}
您可以根据自己的需要获得包含数据的地图。如果有帮助,请告诉我
关心道格拉斯