how to print all enum value in java?

前端 未结 6 1036
自闭症患者
自闭症患者 2021-01-03 21:49
enum generalInformation {
    NAME {
        @Override
        public String toString() {
            return \"Name\";
        }
    },
    EDUCATION {
        @Over         


        
6条回答
  •  耶瑟儿~
    2021-01-03 22:23

    Firstly, I would refactor your enum to pass the string representation in a constructor parameter. That code is at the bottom.

    Now, to print all enum values you'd just use something like:

    // Note: enum name changed to comply with Java naming conventions
    for (GeneralInformation info : EnumSet.allOf(GeneralInformation.class)) {
        System.out.println(info);
    }
    

    An alternative to using EnumSet would be to use GeneralInformation.values(), but that means you have to create a new array each time you call it, which feels wasteful to me. Admittedly calling EnumSet.allOf requires a new object each time too... if you're doing this a lot and are concerned about the performance, you could always cache it somewhere.

    You can use GeneralInformation just like any other type when it comes to parameters:

    public void doSomething(GeneralInformation info) {
        // Whatever
    }
    

    Called with a value, e.g.

    doSomething(GeneralInformation.PHONE);
    

    Refactoring using a constructor parameter

    public enum GeneralInformation {
        NAME("Name"),
        EDUCATION("Education"),
        EMAIL("Email"),
        PROFESSION("Profession"),
        PHONE("Phone");
    
        private final String textRepresentation;
    
        private GeneralInformation(String textRepresentation) {
            this.textRepresentation = textRepresentation;
        }
    
        @Override public String toString() {
             return textRepresentation;
        }
    }
    

    With your current values, you could actually just convert the name to title case automatically - but that wouldn't be very flexible for the long term, and I think this explicit version is simpler.

提交回复
热议问题