zoukankan      html  css  js  c++  java
  • java的foreach(增强for循环)

    今天接触了一个以前看到过但完全朦胧的东西->那就是foreach循环,网上查阅后得到语法如下

    for(元素类型  元素名称 : 遍历数组(集合)(或者能进行迭代的)){

      语句

    }

    由于for括号内没有逻辑表达式,所以它适用于循环次数不知道的情况下会使得代码更加简便(暂时这么理解,具体与for循环之间的效率的区别未知)

    这个增强的for循环,对map类的键值对,也可以使用,例子如下:

     1 public class Test{
     2     public static void main(String[] args) {
     3        Map<String,Integer> testmap = new LinkedHashMap<String, Integer>();
     4        //这里的Integer不能替换为int(似乎这里的类型定义不能使用基本类型,只能使用基本类型的包装类)
     5         testmap.put("s1",1);
     6         testmap.put("s2",2);
     7         testmap.put("s3",3);
     8         //Map.Entry<String,Integer>可以算是一个类型,表明这个键值对集合里键值对的类型
     9         for(Map.Entry<String,Integer> s : testmap.entrySet()){
    10             System.out.println("'" + s.getKey() + "':" + s.getValue());
    11         }
    12     }
    13 }

    在使用foreach时,不能对数组(集合)做添加删除,因为使用foreach时数组(集合)已被锁定不能修改,否则会报出java.util.ConcurrentModificationException异常

    引用:https://www.cnblogs.com/XiaojianGo/p/7471860.html

  • 相关阅读:
    C#:正则表达式
    jsp:
    关于博客的设置
    登录注册案例—MongoDB数据库连接
    cookie封装
    博客样式
    自己的博客
    CentOS7 启动docker.service失败
    合并多个jar包,并通过私服依赖
    springboot+支付宝条码支付开发详解
  • 原文地址:https://www.cnblogs.com/MYoda/p/11139413.html
Copyright © 2011-2022 走看看