检查enum是否有多个值

hal*_*oei 4 java enums conditional-statements

我有一个枚举 FileType

public static enum FileType {
  CSV, XML, XLS, TXT, FIXED_LENGTH
}

FileType fileType = FileType.CSV;
Run Code Online (Sandbox Code Playgroud)

是否有更好(更清洁)的方法来检查fileType多个值而不是以下(像"myString".matches("a|b|c");)?

if(fileType == FileType.CSV || fileType == FileType.TXT || fileType == FileType.FIXED_LENGTH) {}
Run Code Online (Sandbox Code Playgroud)

Kon*_*kov 11

为什么不使用switch:

switch(fileType) {
   case CSV:
   case TXT:
   case FIXED_LENGTH:
       doSomething();
       break;
}
Run Code Online (Sandbox Code Playgroud)

这与if语句检查相同,但它更具可读性,imho.


khe*_*ood 10

选项1:在枚举中添加一个布尔字段.

public static enum FileType {
    CSV(true), XML(false), XLS(false), TXT(true), FIXED_LENGTH(true);

    private final boolean interesting;

    FileType(boolean interesting) {
        this.interesting = interesting;
    }
    public boolean isInteresting() {
        return this.interesting;
    }
}

...

if (fileType!=null && fileType.isInteresting()) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

选项2:使用EnumSet. EnumSets使用引擎盖下的位域,因此它们非常快速且内存不足.

Set<FileType> interestingFileTypes = EnumSet.of(FileType.CSV, FileType.TXT, FileType.FIXED_LENGTH);
...
if (interestingFileTypes.contains(fileType)) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

选项3:使用a switch,正如kocko建议的那样

  • + 1 提及 EnumSet。请注意,“EnumSet”只是“Set”的另一种实现,因此您可以编写:“Set&lt;FileType&gt;interestingFileTypes = EnumSet.of(...);” (2认同)

hal*_*oei 7

我最终写了一个方法:

public static enum FileType {
  CSV, XML, XLS, TXT, FIXED_LENGTH;

  // Java < 8
  public boolean in(FileType... fileTypes) {
    for(FileType fileType : fileTypes) {
      if(this == fileType) {
        return true;
      }
    }

    return false;
  }

  // Java 8
  public boolean in(FileType... fileTypes) {
    return Arrays.stream(fileTypes).anyMatch(fileType -> fileType == this);
  }
}
Run Code Online (Sandbox Code Playgroud)

进而:

if(fileType.in(FileType.CSV, FileType.TXT, FileType.FIXED_LENGTH)) {}
Run Code Online (Sandbox Code Playgroud)

漂亮干净!

  • 这与其他一些人的建议基本相同。如果您接受他们的回答就好了,因为他们会花时间帮助您。 (5认同)