啊满

导航

Enumeration - 枚举类

Enumeration(枚举)接口的作用和Iterator类似,只提供了遍历Vector和HashTable类型集合元素的功能,不支持元素的移除操作。

在Java中,Enumeration是一个接口,用于遍历集合类中的元素。它是Java早期的遗留接口,已经被Iterator接口取代。然而,有些旧的代码库或第三方库仍然使用Enumeration接口,因此了解如何遍历Enumeration对象仍然是很有价值的。

一、Enumeration对象的遍历方法

1. 创建Enumeration对象

首先,需要获取一个Enumeration对象。通常,Enumeration对象是由集合类的方法返回的,例如Vector.elements()方法返回一个Enumeration对象。

Vector<String> vector = new Vector<>();
vector.add("Apple");
vector.add("Banana");
vector.add("Orange");

Enumeration<String> enumeration = vector.elements();

2. 使用hasMoreElements()方法判断是否还有元素

在遍历Enumeration对象之前,需要使用hasMoreElements()方法检查是否还有更多的元素可遍历。该方法返回一个布尔值,表示是否存在下一个元素。

while (enumeration.hasMoreElements()) {
    // 遍历代码
}

3. 使用nextElement()方法获取下一个元素

如果hasMoreElements()方法返回true,则可以使用nextElement()方法获取下一个元素。该方法返回Enumeration对象中的下一个元素,如果没有更多元素,则抛出NoSuchElementException异常。

while (enumeration.hasMoreElements()) {
    String element = enumeration.nextElement();
    // 处理元素的代码
}

4. 完整的遍历Enumeration对象的代码示例

import java.util.Enumeration;
import java.util.Vector;

public class EnumerationExample {
    public static void main(String[] args) {
        Vector<String> vector = new Vector<>();
        vector.add("Apple");
        vector.add("Banana");
        vector.add("Orange");

        Enumeration<String> enumeration = vector.elements();

        while (enumeration.hasMoreElements()) {
            String element = enumeration.nextElement();
            System.out.println(element);
        }
    }
}

 

 

二、Java8中Enumeration接口的源码

public interface Enumeration<E> {
    /**
     * Tests if this enumeration contains more elements.
     *
     * @return  <code>true</code> if and only if this enumeration object
     *           contains at least one more element to provide;
     *          <code>false</code> otherwise.
     */
    boolean hasMoreElements();//判断是否包含元素

    /**
     * Returns the next element of this enumeration if this enumeration
     * object has at least one more element to provide.
     *
     * @return     the next element of this enumeration.
     * @exception  NoSuchElementException  if no more elements exist.
     */
    E nextElement();//获得下一个元素
}

通过Enumeration的源码分析可得,Enumeration有两个方法:

(1)boolean hasMoreElements();  //是否还有元素,如果返回true,则表示至少含有一个元素

(2)E nextElement();  //如果Enumeration枚举对象还有元素,返回对象中的下一个元素,否则抛出NoSuchElementException异常。

简单示例:

public class TestEnumeration{

  public static void main(String[] args){
        Vector v = new Vector();
        v.addElement("Lisa");
        v.addElement("Billy");
        v.addElement("Mr Brown");
        Enumeration e = v.elements();//返回Enumeration对象
        while(e.hasMoreElements()){
            String value = (String)e.nextElement();//调用nextElement方法获得元素
            System.out.print(value);
        }
    }
}

 


 

posted on 2024-02-23 10:38  啊满  阅读(99)  评论(0)    收藏  举报