簡體   English   中英

Java 6中的空枚舉

[英]Empty Enumeration in Java 6

Java 7提供了方便的方法

Collections.emptyEnumeration()

但這在Java 6中不可用。

是否有一個空的枚舉類潛伏在JDK的其他地方,或者我需要自己滾動嗎?

你可以簡單地使用

Collections.enumeration(Collections.emptyList());

JDK 6中沒有空的Enumeration,但您可以使用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(); }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM