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

    二、迭代器

     1 import java.util.ArrayList;
     2 import java.util.Collection;
     3 import java.util.Iterator;
     4 
     5 public class Demo01 {
     6     /*
     7      * 集合中的迭代器:获取集合中元素方法
     8      * 接口Iterator两个抽象方法:
     9      *             boolean hasNext();判断集合中还有没有可以被取出的元素
    10        *            next();取出集合的下一个元素
    11      * Iterator接口实现类:
    12      *             Collection接口定义方法:Iterator iterator();
    13      *             ArrayList 重写方法iterator();返回了Iterator接口的实现类的对象
    14      *             使用ArrayList集合的对象
    15      *                 Iterator it = arr.iterator();结果就是 Iterator接口的实现类的对象
    16      *                 it是接口的实现类的对象,调用方法hasNext和next集合元素迭代
    17      */
    18     public static void main(String[] args) {
    19         Collection<String> col = new ArrayList<>();
    20         col.add("ad");
    21         col.add("as");
    22         col.add("ds");
    23         col.add("gr");
    24         
    25         Iterator<String> it = col.iterator();
    26         //boolean b = it.hasNext();
    27         //System.out.println(b);
    28         //String s = it.next();
    29         //System.out.println(s);
    30         
    31         while(it.hasNext()){
    32             String s = it.next();
    33             System.out.println(s);
    34         }    
    35     }        
    36 }

     1 public class Demo02 {
     2     public static void main(String[] args) {
     3         function();
     4     }
     5     //集合可以存储任意类型的对象
     6     //集合中,不指定存储的数据类型,集合什么都存
     7     private static void function() {
     8         Collection col = new ArrayList();
     9         col.add("asd");
    10         col.add("dsf");
    11         
    12         //迭代器获取
    13         Iterator it = col.iterator();
    14         while(it.hasNext()){
    15             Object obj = it.next();
    16             System.out.println(obj);
    17             String s = (String)obj;
    18             System.out.println(s.length());
    19         }
    20     }    
    21 }
  • 相关阅读:
    在eclipse中进行HotSpot的源码调试
    CentOS6.5上编译OpenJDK7源码
    商城楼层跳转
    javascript原生百叶窗
    javascript原生轮播
    Canvas计时器
    纯js模拟 radio和checkbox控件
    纯js日历
    关于匿名函数,闭包和作用域链
    端口占用问题
  • 原文地址:https://www.cnblogs.com/Nelsoner/p/6675726.html
Copyright © 2011-2022 走看看