加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

是否可以在Java中编写“foreach”函数?

发布时间:2020-12-15 02:06:12 所属栏目:Java 来源:网络整理
导读:在 PHP中,可以做foreach($array as $key = $value){//代码.是否可以在Java中创建一个函数来执行foreach(arr,function(key,value){//代码});? 我不是很擅长Java.要使功能起作用,它必须接受所有数据类型.另外,我不确定是否可以在Java中使用回调函数. 附: “不
在 PHP中,可以做foreach($array as $key => $value){//代码.是否可以在Java中创建一个函数来执行foreach(arr,function(key,value){//代码});?

我不是很擅长Java.要使功能起作用,它必须接受所有数据类型.另外,我不确定是否可以在Java中使用回调函数.

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

解决方法

是的你可以:

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

这也适用于其他课程.

UPDATE

遍历List(数组或链表)时,索引将是索引.您将需要使用替代整数来保存索引:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读