java - 了解枚举器的枚举集

标签 java methods enums enumset method-declaration

据我了解,使用 EnumSet 会更容易、更清晰。并且 Set专为与枚举器一起使用而设计。我的问题是我们是否应该考虑使用 EnumSet每次我们需要维护一些枚举器的集合时。例如,我有以下枚举:

public enum ReportColumns{
    ID,
    NAME,
    CURRENCY
    //It may contain much more enumerators than I mentioned here

    public int getMaintenanceValue(){ 
        //impl
    }
}

我需要在方法中使用一些枚举集合:

public void persist(Collection<ReportColumns> cols){
    List<Integer> ints = new LinkedList<>();
    for(ReportColumn c: cols){
        ints.add(c.getMaintenanceValue());
    }
    //do some persistance-related operations
}

所以,如果我不关心集合是否有序,我应该使用 EnumSet<E>每次都为了提高性能?

最佳答案

根据经验,每当您创建枚举集合并且不关心它们的顺序时,您都应该创建一个EnumSet。正如您所提到的,它会让您的性能略有提高(事实上,我知道的大多数静态代码分析工具实际上都会警告不要使用它)。

对于方法声明,我不会。作为另一个经验法则,方法应该使用仍然有意义的“最高”类型。该方法的公共(public)契约应该是“给我一堆枚举,我将保留它们”。该方法不应该关心传递什么集合,因此强制参数类型为 EnumSet 是没有意义的。如果您传递的具体类型确实是 EnumSet,那么您无论如何都会获得所有性能优势。

关于java - 了解枚举器的枚举集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31239368/

相关文章:

c# - 为什么 C# 编译器允许空枚举?

带有空格的Java枚举元素?

java - 接收百分比编码的 url

java - 从onetomany hibernate 删除

javax.net.ssl.SSLHandshakeException : "Remote host closed connection during handshake" opening an HTTPS page with HTMLUnit

javascript - ES6 : How may one reference an instance method bound to "this"?

jQuery - 单击并打开

java - Spring 安全: Multiple HTTP Config not working

python - 从类方法中始终使用 'return' 是最佳实践吗

c# - 使用 using 指令在 C# 中缩短带有别名的枚举声明