• Java 增强for循环 泛型


    增强for循环
    专门用来遍历数组和集合的。它的内部原理其实是个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作。
    格式:
    for(元素的数据类型 变量 : Collection集合or数组){
    }
    例子

    public static void main(String[] args) {
    //		普通for
    		Collection<Person>col = new ArrayList<Person>();
    		col.add(new Person("熊大",22));
    		col.add(new Person("熊二",10));
    		col.add(new Person("吉吉国王",30));
    		ArrayList<Person> list = (ArrayList<Person>)col;
    		for(int i =0;i<list.size();i++) {
    			System.out.println(list.get(i));
    		}
    //		增强for   没有下标
    		/*for(要遍历的数据类型 变量名:容器名){
    		 }*/
    		for(Person p:col) {
    			System.out.println(p);
    		}
    

      

    增强for循环和老式的for循环有什么区别?
    遍历数组,集合时,如果仅为遍历,可以使用增强for,如果要对数组的元素进行操作,使用普通for循环可以通过下标操作。
    泛型

    泛型,用来灵活地将数据类型应用到不同的类、方法、接口当中。将数据类型作为参数进行传递。

    优点
    将运行时期的ClassCastException,转移到了编译时期变成了编译失败。
    避免了类型强转的麻烦。泛型不进class文件

    例子

     public static void main(String[] args) {
            List<String> list = new ArrayList<String>();
            list.add("abc");
            list.add("oracle");
            //list.add(5);//当集合明确类型后,存放类型不一致就会编译报错
            //集合已经明确具体存放的元素类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素类型
            Iterator<String> it = list.iterator();
            while(it.hasNext()){
        String str = it.next();
    //当使用Iterator<String>控制元素类型后,就不需要强转了。获取到的元素直接就是String类型
                System.out.println(str.length());
            }
        }
    

      

  • 相关阅读:
    单据的多个状态字段
    Win7 如何阻止程序联网
    强制关机.bat
    Delphi Class of
    坐标转换 GetCursorPos与转换
    Delphi 的RTTI机制浅探-2
    Delphi 的RTTI机制浅探-1
    Delphi 的RTTI机制-3
    Delphi 的RTTI机制-2
    Delphi 的RTTI机制-1
  • 原文地址:https://www.cnblogs.com/cgj1994/p/9762905.html
Copyright © 2020-2023  润新知