zoukankan      html  css  js  c++  java
  • 集合框架03

    三、增强for循环(foreach)

    1 //好处:代码少,方便遍历
    2 //弊端:没有索引,不能操作容器里的元素
    3 private static void function() {
    4     int[] arr = {3,1,4,5,6};
    5     for(int i:arr){
    6         System.out.println(i);
    7     }
    8 }

    四、泛型

       /*
     2  * JDK1.5 出现新的安全机制,保证程序的安全性
     3  *   泛型: 指明了集合中存储数据的类型  <数据类型>
     4  */
     5 
     6 public class GenericDemo {
     7     public static void main(String[] args) {
     8         function();
     9     }
    10     
    11     public static void function(){
    12         Collection<String> coll = new ArrayList<String>();
    13         coll.add("abc");
    14         coll.add("rtyg");
    15         coll.add("43rt5yhju");
    16 //        coll.add(1);
    17         
    18         Iterator<String> it = coll.iterator();
    19         while(it.hasNext()){
    20             String s = it.next();
    21             System.out.println(s.length());
    22         }
    23     }
    24 }
    /*
     *  带有泛型的接口
     *  
     *  public interface List <E>{
     *    abstract boolean add(E e);
     *  }
     *  实现类,先实现接口,不理会泛型
     *  public class ArrayList<E> implements List<E>{
     *  }
     *  调用者 : new ArrayList<String>() 后期创建集合对象的时候,指定数据类型
     *  
     *  实现类,实现接口的同时,也指定了数据类型
     *  public class XXX implements List<String>{
     *  }
     *  new XXX()
     */
     1 /*
     2  *  泛型的通配符
     3  */
     4 public class GenericDemo {
     5     public static void main(String[] args) {
     6         ArrayList<String> array = new ArrayList<String>();
     7         
     8         HashSet<Integer> set = new HashSet<Integer>();
     9         
    10         array.add("123");
    11         array.add("456");
    12         
    13         set.add(789);
    14         set.add(890);
    15         
    16         iterator(array);
    17         iterator(set);
    18     }
    19     /*
    20      *  定义方法,可以同时迭代2个集合
    21      *  参数: 怎么实现 , 不能写ArrayList,也不能写HashSet
    22      *  参数: 或者共同实现的接口
    23      *  泛型的通配,匹配所有的数据类型  ?
    24      */
    25     public static void iterator(Collection<?> coll){
    26         Iterator<?> it = coll.iterator();
    27         while(it.hasNext()){
    28             //it.next()获取的对象,什么类型
    29             System.out.println(it.next());
    30         }
    31     }
    32 } 
  • 相关阅读:
    定时任务(收集)
    命令学习(收集)
    查看进程运行时间
    Linux 中挂载 ISO 文件
    9.已知三边计算三角形的面积公式
    8.输入一个大写字母,要求小写字母输出
    1.输出三个数中的最大值
    2.依次从大到小输出三个数
    3.计算1+2+3+....100=?
    4.计算1*2*3*4........*100=?
  • 原文地址:https://www.cnblogs.com/Nelsoner/p/6677685.html
Copyright © 2011-2022 走看看