简体   繁体   中英

Enum with array/list values

if (isProductDeliverable) {
  REQUIRED_FIELDS = Arrays.asList(new String[] { Fields.NAME, Fields.EMAIL, Fields.ADDRESS });
} else {
  REQUIRED_FIELDS = Arrays.asList(new String[] { Fields.NAME, Fields.EMAIL });
}

Instead of this, I want to have a predefined enum with two fields - REQUIRED_FIELDS_FOR_DELIVERABLE_PRODUCTS and REQUIRED_FIELDS_FOR_DOWNLOADABLE_PRODUCTS

I know the theory of enums but I've never used them so I cant figure out a way how to do this.

Or maybe a way to ask for the required fields by passing this "isProductDeliverable" boolean and get the correct array of fields?

Enums can have data and behaviour much like classes. Something like this should work...

public enum RequiredFields {
    REQUIRED_FIELDS_FOR_DELIVERABLE_PRODUCTS( Fields.NAME, Fields.EMAIL, Fields.ADDRESS ),
    REQUIRED_FIELDS_FOR_DOWNLOADABLE_PRODUCTS( Fields.NAME, Fields.EMAIL );

    private List<String> fields;
    private RequiredFields(String... fields){
        this.fields = Arrays.asList(fields);
    }
    public List<String> getFields(){
        return fields;
    }
}

Further improvement:

In above code, the fields property is still mutable. Someone could do REQUIRED_FIELDS_FOR_DELIVERABLE_PRODUCTS.getFields().add(..) which would beat the whole purpose of having the enum in the first place.

Better implementation for the constructor would be:

private RequiredFields(String... fields){
    this.fields = ImmutableList.copyOf(fields); //com.google.common.collect.ImmutableList
}

For creating immutable list of objects, from Java 9 you can use List.of static method. So you can create something like:

   Enum1("a","b"),
   Enum2("c","d")
   private String fields;
   EnumClassName(String...args) {
    this.fields = List.of(args);
   }
  }

In the calling method you can call like list = Enum1.fields; Hoping this clears your understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM