检查enum是否有多个值

问题描述 投票:4回答:4

我有一个枚举FileType

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

FileType fileType = FileType.CSV;

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

if(fileType == FileType.CSV || fileType == FileType.TXT || fileType == FileType.FIXED_LENGTH) {}
java enums conditional-statements
4个回答
11
投票

为什么不使用switch

switch(fileType) {
   case CSV:
   case TXT:
   case FIXED_LENGTH:
       doSomething();
       break;
}

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


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()) {
    ...
}

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

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

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


3
投票

我最后写了一个方法:

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);
  }
}

然后:

if(fileType.in(FileType.CSV, FileType.TXT, FileType.FIXED_LENGTH)) {}

干净整洁!


-1
投票

添加一个不同的例子:

public class JavaApplication {

    public enum CustomerStatus {
        ACTIVE("Active"),
        DISCONNECTED("Disconnected"),
        PENDING("Pending"),
        CANCELLED("cancelled"),
        NEW("new");

    }

    public static void main(String[] args) {
        EnumSet<CustomerStatus> setA = EnumSet.of(CustomerStatus.ACTIVE, CustomerStatus.NEW);
        EnumSet<CustomerStatus> setB = EnumSet.of(CustomerStatus.PENDING, CustomerStatus.CANCELLED);
        if (setA.contains(CustomerStatus.ACTIVE)) {
            System.out.println("ACTIVE : customer active");
        }
        if (setB.contains(CustomerStatus.ACTIVE)) {
            System.out.println("ACTIVE: Customer is no longer active");
        }
        if (setB.contains(CustomerStatus.CANCELLED)   {
            System.out.println("CANCELLED: Customer is no longer active");
        }

    }
}


**Output**:
ACTIVE : customer active
CANCELLED: Customer is no longer active
© www.soinside.com 2019 - 2024. All rights reserved.