zoukankan      html  css  js  c++  java
  • 集合输出接口-Iterator迭代输出-古老枚举输出:Enumeration

    1、Iterator迭代输出(95%)

    Iterator是集合输出的主要接口,那么此接口定义如下:

    public interface Iterator<E> {
            public boolean hasNext() ; // 判断是否还有下一个数据 
            public E next() ;   // 取得当前数据 
    }        

    实现代码:

     1 package cn.demo;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Iterator;
     5 import java.util.List;
     6 
     7 public class Test {
     8     public static void main(String[] args) throws Exception {
     9     List<String> all = new ArrayList<String>();
    10     all.add("java");
    11     all.add("jsp");
    12     all.add("oracle");
    13     Iterator<String> iter = all.iterator();
    14     while(iter.hasNext()){
    15         String str = iter.next();
    16         System.out.println(str);
    17     }
    18     }
    19 }

    结果:

    java
    jsp
    oracle

    2、古老枚举输出:Enumeration(4.96%)

    这个接口的定义如下:

    public interface Enumeration<E> {
            public boolean hasMoreElements() ; // 判断是否有下一个元素                              
            public E nextElement() ; // 取得当前元素
     }     

    Collection接口里面并没有定义取得有Enumeration接口对象的方法,而这个接口的实例化对象取得依靠的是Vector类。

    在此类定义有方法:public Enumeration<E> elements();

    代码如下:

     1 package cn.demo;
     2 
     3 import java.util.Enumeration;
     4 import java.util.Vector;
     5 
     6 public class Test {
     7     public static void main(String[] args) throws Exception {
     8         Vector<String> all = new Vector<String>();
     9         all.add("java");
    10         all.add("jsp");
    11         all.add("oracle");
    12         Enumeration<String> enu = all.elements();
    13         while(enu.hasMoreElements()){
    14             System.out.println(enu.nextElement());
    15         }
    16     }
    17 }

    结果:

    java
    jsp
    oracle

    总结:1、 Iterator属于集合的最标准做法,两个方法:hashNext()、next();

       2、 Enumeration属于Vector遗留方法,两个方法:hasMoreElements()、nextElement()。

  • 相关阅读:
    VueCLI3如何更改安装时的包管理器
    查天气43课-46课
    【Python第31课到42课】
    【Python第16课到30课 】
    Python笔记
    【AC】九度OJ题目1153:括号匹配问题
    【AC】九度OJ题目1436:Repair the Wall
    【WA】九度OJ题目1435:迷瘴
    Matlab图片改颜色通道不改名存储
    [Linux 操作] awk操作の 打印图片路径
  • 原文地址:https://www.cnblogs.com/liyang31/p/5812008.html
Copyright © 2011-2022 走看看