Java枚举的打印_如何在java中打印所有枚举值?

首先,我会重构您的枚举在构造函数参数中传递字符串表示形式。该代码位于底部。

现在,打印你只是使用的东西像所有枚举值:

// Note: enum name changed to comply with Java naming conventions

for (GeneralInformation info : EnumSet.allOf(GeneralInformation.class)) {

System.out.println(info);

}

使用EnumSet将是一个替代使用GeneralInformation.values(),但是这意味着你必须每次创建一个新的数组你称之为,这让我觉得很浪费。无可否认,要求EnumSet.allOf每次都需要一个新的对象......如果你正在做这个很多并且关心性能,你总是可以将它缓存在某个地方。

您可以使用GeneralInformation就像任何其他类型的,当涉及到的参数:

public void doSomething(GeneralInformation info) {

// Whatever

}

一个值,例如调用

doSomething(GeneralInformation.PHONE);

使用构造函数参数

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;

}

}

与您当前值,你可以实际上只是自动转换名称首字母大写重构 - 但是这不会很从长远来看是灵活的,我认为这个明确的版本更简单。

你可能感兴趣的:(Java枚举的打印)