2015-02-10 63 views
5

爪哇7提供了方便的方法空枚举6

Collections.emptyEnumeration()

但是,这不是在可用的Java 6.

是否有一个空的枚举类在JDK别处潜伏,或做我需要推出自己的?

回答

14

您可以简单地使用

Collections.enumeration(Collections.emptyList()); 
5

存在JDK 6没有空枚举,但你可以使用源代码从JDK 7

/* 
    * taken from jdk source 
    * @since 1.7 
    */ 
    public static <T> Enumeration<T> emptyEnumeration() { 
     return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION; 
    } 

    private static class EmptyEnumeration<E> implements Enumeration<E> { 
     static final EmptyEnumeration<Object> EMPTY_ENUMERATION 
      = new EmptyEnumeration<>(); 

     public boolean hasMoreElements() { return false; } 
     public E nextElement() { throw new NoSuchElementException(); } 
    }