$value){//codes。是否可以在 Java 中创建一个函数来执行 foreach(arr,function(key,-6ren">
gpt4 book ai didi

java - 是否可以用 Java 编写 "foreach"函数?

转载 作者:搜寻专家 更新时间:2023-11-01 03:57:53 24 4
gpt4 key购买 nike

在 PHP 中,可以执行 foreach($array as $key=>$value){//codes。是否可以在 Java 中创建一个函数来执行 foreach(arr,function(key,value){//codes});

我不太擅长 Java。要使函数正常工作,它必须接受所有数据类型。另外,我不确定是否可以在 Java 中使用回调函数。

附言“不可能”是一个有效的答案,谢谢!

最佳答案

是的,你可以:

List<String> ls = new ArrayList();
ls.add("Hello");
ls.add("world");
//your foreach sentence
for(String s : ls) {
System.out.println(s);
}

这也适用于其他类。

更新

当你遍历一个列表(数组或链表)时,索引就是索引。您将需要使用替代整数来保存索引:

List<String> ls = new ArrayList();
ls.add("Hello");
ls.add("world");
//your foreach sentence
int index = 0;
for(String s : ls) {
System.out.println("index: " + index);
System.out.println(s);
//put your logic here...
//at the end, update the index manually
index++;
}

如果你需要遍历一个Map(基于键,值的结构)那么你应该使用@LukasEder描述的方法(改编他的代码):

Map<K, V> array = new HashMap<K, V>();
for (Entry<K, V> entry : array.entrySet()) {
// You have to explicitly call your callback. There is no "callback-syntax"
// to the Java "foreach" loop
System.out.println("key: " + entry.getKey());
System.out.println("value: " + entry.getValue());
//put your logic here...
}

关于java - 是否可以用 Java 编写 "foreach"函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10029881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com