Enumeration接口

在学习properties类的过程使用到Enumeration接口,因此学习记录下。

Enumeration接口中定义了一些方法,通过这些方法可以枚举(一次获得一个)对象集合中的元素。这种传统接口已被迭代器取代,虽然Enumeration 还未被遗弃,但在现代代码中已经被很少使用了。尽管如此,它还是使用在诸如Vector和Properties这些传统类所定义的方法中,除此之外,还用在一些API类,并且在应用程序中也广泛被使用

1.java.util 接口 Enumeration<E>

例如,要输出 Vector<E> v 的所有元素,可使用以下方法:

   for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
       System.out.println(e.nextElement());

上面是jdk文档给的一个例子,Enumeration接口可以使用来遍历vector中的元素列表

2.源码

/**
 * 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();

3.方法的详细信息

  • hasMoreElements
boolean hasMoreElements()
  • 测试此枚举是否包含更多的元素。

  • 返回:

    当且仅当此枚举对象至少还包含一个可提供的元素时,才返回 true;否则返回 false


  • nextElement
E nextElement()

如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素。

  • 返回:

    此枚举的下一个元素。

4.在properties类中的使用

    /**
     * Returns an enumeration of all the keys in this property list,
     * including distinct keys in the default property list if a key
     * of the same name has not already been found from the main
     * properties list.
     *
     * @return  an enumeration of all the keys in this property list, including
     *          the keys in the default property list.
     * @throws  ClassCastException if any key in this property list
     *          is not a string.
     * @see     java.util.Enumeration
     * @see     java.util.Properties#defaults
     * @see     #stringPropertyNames
     */
    public Enumeration<?> propertyNames() {
        Hashtable<String,Object> h = new Hashtable<>();
        enumerate(h);
        return h.keys();
    }

propertyNames()方法返回一个存放所有key的枚举列表

使用如下

Properties prop = new Properties();
Enumeration enumeration =  prop.propertyNames();
while(enumeration.hasMoreElements()){
    String key = (String)enumeration.nextElement();
    String value = prop.getProperty(key);
    System.out.println(key+":"+value);
}

5.在vector中的使用

这里等学到vector的知识来继续更新....

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容